小编典典
与几乎所有“如何在PHP中执行SQL”问题一样,您 实际上 应该使用准备好的语句。这并不难:
$ids = array(2, 4, 6, 8);
// prepare an SQL statement with a single parameter placeholder
$sql = "UPDATE MyTable SET LastUpdated = GETDATE() WHERE id = ?";
$stmt = $mysqli->prepare($sql);
// bind a different value to the placeholder with each execution
for ($i = 0; $i < count($ids); $i++)
{
$stmt->bind_param("i", $ids[$i]);
$stmt->execute();
echo "Updated record ID: $id\n";
}
// done
$stmt->close();
或者,您可以这样做:
$ids = array(2, 4, 6, 8);
// prepare an SQL statement with multiple parameter placeholders
$params = implode(",", array_fill(0, count($ids), "?"));
$sql = "UPDATE MyTable SET LastUpdated = GETDATE() WHERE id IN ($params)";
$stmt = $mysqli->prepare($sql);
// dynamic call of mysqli_stmt::bind_param hard-coded eqivalent
$types = str_repeat("i", count($ids)); // "iiii"
$args = array_merge(array($types), $ids); // ["iiii", 2, 4, 6, 8]
call_user_func_array(array($stmt, 'bind_param'), ref($args)); // $stmt->bind_param("iiii", 2, 4, 6, 8)
// execute the query for all input values in one step
$stmt->execute();
// done
$stmt->close();
echo "Updated record IDs: " . implode("," $ids) ."\n";
// ----------------------------------------------------------------------------------
// helper function to turn an array of values into an array of value references
// necessary because mysqli_stmt::bind_param needs value refereces for no good reason
function ref($arr) {
$refs = array();
foreach ($arr as $key => $val) $refs[$key] = &$arr[$key];
return $refs;
}
根据需要为其他字段添加更多参数占位符。
选哪一个?
第一种变体可迭代处理可变数量的记录,从而多次访问数据库。这对于UPDATE和INSERT操作最有用。
第二种变体也适用于可变数量的记录,但是它只命中一次数据库。这比迭代方法高效得多,显然,您只能对所有受影响的记录执行相同的操作。这对于SELECT和DELETE操作,或者要更新具有相同数据的多条记录时最有用。
为什么要准备陈述?
预备语句更安全,因为它们使SQL注入攻击变得不可能。这是使用准备好的语句的主要原因,即使编写它们是更多的工作。养成明智的习惯:即使您认为“不是真的”,也要始终使用准备好的语句。疏忽会来咬你(或你的顾客)。
与将多个完整的SQL字符串发送到数据库相比,以不同的参数值多次重复使用同一条准备好的语句效率更高,因为数据库只需要编译一次该语句即可,并且也可以重新使用它。
仅将参数值发送到上的数据库execute(),因此当重复使用时,需要较少的数据通过网络。
在更长的循环中,使用准备好的语句和发送纯SQL之间的执行时间差异将变得明显。
2020-05-17