Hi,
I have been working through this book: PHP and MySQL: Novice to Ninja. All good so far but I’m struggling to get my head around the section below. Does anyone have a CLEAR explanation?
*** page 253-4
function updateJoke($pdo, $fields) {
$query = ' UPDATE `joke` SET ';
foreach ($array as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ','
}
$query = rtrim($query, ',');
$query .= ' WHERE `id` = :primaryKey';
// Set the :primaryKey variable
$fields['primaryKey'] = $fields['id'];
query($pdo, $query, $fields);
}
You’ll notice I set the primaryKey key manually with this line:
/ Set the :primaryKey variable
$fields['primaryKey'] = $fields['id'];
This is so that the WHERE clause in the query is provided with the relevant ID to
update. :id can’t be used, because it has already been used in the query, and each
parameter needs a unique name.
With this version of the updateJoke function, it’s now possible to run it as we
designed earlier:
updateJoke($pdo, [
'id' => 1,
'joketext' => '!false - it\'s funny because it\'s true']
);
Thanks in advance.
Mike