Thursday 11 April 2019

php - MySQLi update query - increment value with parameterized query



Essentially I'm just trying to increment a value in columnA by 1, but I want to do so with a parameterized mysqli query. The existing value may be null, blank or a number, but if it is the former two, then the query should just treat it as 0 and increment it by 1. The example here does so without a parameter.



My existing code is here - stuck on the bind_param step:



$prepare = $this -> db -> prepare("UPDATE userinfo SET idarray = ?, currentkey = ? WHERE id = ?");
$prepare -> bind_param('sii', serialize($numbers), currentkey + 1, $ID);
$prepare -> execute();


if ($prepare -> errno)
{
echo $prepare -> error;
}

$prepare -> close();

Answer



Why do you try to put a record value currentkey + 1 (non PHP variable) into your prepared statement?




Can you just try:





//...
$prepare = $this->db->prepare("UPDATE userinfo SET idarray = ?, currentkey = currentkey + 1 WHERE id = ?");
$prepare->bind_param('si', serialize($numbers), $ID);
$prepare->execute();
// ...



If you think about it your currentkey + 1 is not a parameter from PHP, your SQL engine knows the value and how to do the sum


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...