我有這個功能內爆修復更新SQL
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key($_POST, array_flip($fieldnames)); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
它輸出例如:UPDATE SET項目PROJECT_NAME = '123',project_bold = '123',project_content = '123',其中ID = '12 '
之前的最後一個逗號是阻止它工作的地方。有沒有辦法避免這種情況?我意識到函數內爆,但我不知道如何在這種情況下使用它。
請修復SQL注入漏洞,並考慮切換到MySqli或PDO擴展來訪問您的數據庫(MySql擴展名爲obselete)。請參閱http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php –