So I’ve created a simple PHP function to ‘UPDATE’ my MySQL row just by updating the array that is received by PHP.
function db_updateproduct(array $new, array $old = array()) {
$diff = array_diff($new, $old);
return 'INSERT INTO table (`'.mysql_real_escape_string(implode(array_keys($diff), '`,`')).'`) VALUES \''.mysql_real_escape_string(implode(array_values($diff), '\',\'')).'\'';
}
…
Update (with Accepted answer)
function db_updateproduct(array $new, array $old = array()) {
$diff = array_diff($new, $old);
return 'INSERT INTO `Product` (`'.implode(array_keys($diff), '`,`').'`) VALUES (\''
.implode(array_map('mysql_real_escape_string', array_values($diff)), '\', \'').'\')';
}
Now…
echo db_updateproduct(array('a' => 'on\'e', 'b' => 'two', 'c' => 'three'));
returns:
INSERT INTO `Product` (`a`,`b`,`c`) VALUES ('on\'e', 'two', 'three')
(As expected/wanted!)
You can run the escape function on the keys and values with
array_map():$escaped_keys = array_map(‘mysql_real_escape_string’, array_keys($diff));
Then you can do your
implode()magic on these two arrays.UPDATE: As @YourCommonSense correctly pointed it out, it does not really make sense to run
mysql_real_escape_string()on values that will be used in the query as field names/table names/etc. It correctly escapes\x00,\n,\r,\,',"and\x1a, but it does NOT escape the backtick, so the query is still vulnerable to attacks.You should validate the field names (so only the expected names can be used) or even better, use prepared queries (I recommend PDO).
Suggested reading: