将MySQL查询转换为具有可能空值的预准备语句

时间:2016-03-27 17:39:42

标签: php mysql mysqli prepared-statement sql-injection

为了防止sql注入,我将查询转换为预处理语句。我还有一个。它也包含一个可能的空值,因此证明它有点困难。

正常:

// Declare $dbc, $varA, $varB, $varC, $ID

$varC = ($varC == '-') ? "NULL" : "'" . $varC . "'";

$query = "UPDATE myTable ";
$query .= "SET VARA = '{$varA}', VARB = '{$varB}', VARC = $varC ";
$query .= "WHERE ID = '{$ID}'";

$result = @mysqli_query($dbc, $query) or die("Error updating record: " . mysqli_error($dbc));

尝试准备好的陈述:

// Declare $dbc, $varA, $varB, $varC, $ID

$varC = ($varC == '-') ? "NULL" : "'" . $varC . "'";

$query = "UPDATE myTable ";
$query .= "SET VARA = ? VARB = ? VARC = ? ";
$query .= "WHERE ID = ?";

$stmt = mysqli_prepare($dbc, $query);
$bind = mysqli_stmt_bind_param($stmt, "ssss", $varA, $varB, $varC, $ID);
$exec = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

1 个答案:

答案 0 :(得分:2)

为什么不

$varC = ($varC == '-') ? null : $varC;

此外,您在查询中缺少逗号

$query .= "SET VARA = ?, VARB = ?, VARC = ? ";

修改 我只是用我的更改运行代码,它似乎工作正常。作为参考,这是我使用的代码:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

$dbc = mysqli_connect("127.0.0.1", "test", "test", "test");


$ID = "1";
$varA = "a";
$varB = "b";
$varC = "-";

$varC = ($varC == '-') ? null : $varC;

$query = "UPDATE myTable ";
$query .= "SET VARA = ?, VARB = ?, VARC = ? ";
$query .= "WHERE ID = ?";

$stmt = mysqli_prepare($dbc, $query);
$bind = mysqli_stmt_bind_param($stmt, "ssss", $varA, $varB, $varC, $ID);
$exec = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

您是否可以尝试将错误报告行添加到代码顶部,看看是否收到任何错误?