That semi-colon isnât at the end of the query, itâs at the end of the line of PHP code. If you wanted to put it at the end of the query, youâd need to edit this line and put it inside the quotes, but I donât think MySQL needs it:
$query .= ' WHERE `id` = :primaryKey';
What is in $query and $fields when you dump them for debugging?
/* Initialize an array */
$attribute_pairs = [];
/* Create the prepared statement string */
foreach ($fields as $key => $value)
{
if($key === 'id') { continue; } // Don't include the id:
$attribute_pairs[] = "{$key}=:{$key}"; // Assign it to an array:
}
/*
* The sql implodes the prepared statement array in the proper format
* and updates the correct record by id.
*/
$sql = 'UPDATE joke SET ';
$sql .= implode(", ", $attribute_pairs) . ' WHERE id =:id';
/* Normally in two lines, but you can daisy chain pdo method calls */
$pdo->prepare($sql)->execute($fields);
return true;
I think the first problem is youâre not setting the proper array $array ? $fields (I think it might be an infinite loop cause the HTTP ERROR 500?) and I would do everything in one function like the above. I donât know if the above will work as I havenât tested it out, but I think it should. I just thought I would give you some think about?
Thatâs probably not helping - the function brings in an array called $fields, but the code uses an array called $array. But I wouldnât expect that to cause an infinite loop, Iâd expect either an error message, or for foreach() to just do nothing as there is no array or object to loop through. When I test it, I just get no fields in the query.
Have a look at the print_r() and var_dump() functions which will show you the contents of variables or arrays at the point that you call those functions. Sometimes itâs as easy to call echo, but you canât do that on an array.
Hey, so am reading version 6? With Tom Butler. And interestingly after a couple more examples posted in the book, Tom/Kevin himself corrected the error but didnât even speak about it so itâs quite confusing.
The book has a lot of errors and fixes which I donât think even Kevin/Tom saw or knew about because they donât talk about them. Am attaching two images to show you what I mean.
So I copy the full code but I get the same error again, so I read further to see if they correct this error and lo and behold they did and again didnât acknowledge it. As you can see, the line;
$query = 'INSERT INTO `joke` ('
is missing a semi-colon. But when I scrolled down further, I see on page 261, that they have added the semi-colon to the code and everything works now.
Itâs quite frustrating to say the least. But I guess Iâll just have to ignore errors as they happen and continue reading hoping they fix the error in their next code post.
It is frustrating, but itâs also quite an easy fix - youâll be aware that virtually no line in PHP wouldnât need a semi-colon on the end, so if you see one missing, you know itâs almost certain that it should have one.