Hi There, hoping someone can help me out of this hole.
I'm creating a function that will update a number of records from an SQL database, the variables that need to be updated are stored in an array ($array) and I want to use the <a href="http://uk2.php.net/manual/en/function.mysql-real-escape-string.php">sprintf / mysql_real_escape_string</a> construction to avoid SQL injection attacks.
$table = "artists"; $row = "1";
$sql = 'sprintf("';
$sql .= "UPDATE %s SET ";
for (reset($array); list($key) = each($array);) {
$sql .= "$key = '%s', ";
$sprint[$i] = $array[$key]; $i++; // counter used for later
}
$sql = substr_replace($sql,"",-2); // trim the last comma and space.
$sql .= " WHERE `pk` = '%s'" . '", ';
$sql .= "mysql_real_escape_string($table), "; // $table contains the tablename.
$count = (count($sprint));
for ($i=0; $i<$count; $i++) { // dump the other escape (%s) values.
$sql .= "mysql_real_escape_string($sprint[$i]), ";
}
$sql .= "mysql_real_escape_string($row));"; // finish it off with the row escape value.
echo "output = $sql";
This will now out put the correct syntax..
$sql wrote:sprintf("UPDATE %s SET name = '%s', label = '%s' WHERE
pk
= '%s'", mysql_real_escape_string(artists), mysql_real_escape_string(deftones24), mysql_real_escape_string(universal), mysql_real_escape_string(1));
but when I try to do a query on it...
if (!$result = mysql_query($sql)) {
die ("SQL FAILED -".mysql_error());
}
I get...
SQL FAILED -You have an error in your SQL syntax near 'sprintf("UPDATE %s SET name = '%s', label = '%s' WHERE
pk
= '%s'", mysql_real_' at line 1
presumably because it is trying to run the whole string including the sprintf bit, instead of actually parsing it.
Anyone know what I'm getting at here? I'm sure I'm missing something really obvious, but it's been bugging me for a while now!
Thanks
Jonny.