简体   繁体   中英

How to debug the concatenation of a SQL query in PHP?

There's something with my query, but I cannot manage to find what.

    $keys = array_keys($fields);
    $values = array_values($fields);

    $sql = "UPDATE " .$table. " SET " .implode("`, `", $keys) ."='".implode("', '", $values) . "' WHERE id={$id}";

And it shows as : UPDATE users SET name , password'Rick is vets', 'sdfg' WHERE id=5

But it has to show as : UPDATE users SET name = 'Rick is vets', password='sdfg' WHERE id=5

$setString='';

foreach($fields as $k=>$v){

$setString .=$k." = '".$v."', ";

}
$setString=rtrim($setString,', ');

include $setString in query

Try looping through the $fields array to create an update string like this:

$update_string='';

foreach ($fields as $key=>$value)
{
    $update_string .= $key."='$value', ";
}

Then remove the last comma character from the string using rtrim() function:

$update_string = rtrim($update_string, ", ");

Then your query becomes:

$sql = "UPDATE " .$table. " SET " .$update_string. " WHERE id={$id}";

This is just to illustrate the concept since your code might still be open to SQL injection attacks, in which case you should use prepared statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM