我有一个充满随机内容项ID的数组.我需要运行一个mysql查询(数组中的id进入WHERE子句),使用数组中的每个ID,按照它们出现在所述数组中的顺序.我该怎么做?
对于数组中的每个ID,这将是一个UPDATE查询.
Tom*_*lak 36
与几乎所有"我如何从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();
Run Code Online (Sandbox Code Playgroud)
或者,您可以这样做:
$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;
}
Run Code Online (Sandbox Code Playgroud)
根据需要为其他字段添加更多参数占位符.
哪一个选?
第一个变体迭代地使用可变数量的记录,多次命中数据库.这对UPDATE和INSERT操作最有用.
第二种变体也可以使用可变数量的记录,但它只能访问数据库一次.这比迭代方法更有效,显然你只能对所有受影响的记录做同样的事情.这对SELECT和DELETE操作最有用,或者当您想要使用相同数据更新多个记录时.
为何准备好陈述?
execute()
,因此重复使用时需要更少的数据通过线路.在较长的循环中,使用预准备语句和发送纯SQL之间的执行时间差异将变得明显.
你可能会追求什么
$ids = array(2,4,6,8);
$ids = implode($ids);
$sql="SELECT * FROM my_table WHERE id IN($ids);";
mysql_query($sql);
Run Code Online (Sandbox Code Playgroud)
否则,出了什么问题
$ids = array(2,4,6,8);
foreach($ids as $id) {
$sql="SELECT * FROM my_table WHERE ID = $id;";
mysql_query($sql);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11054 次 |
最近记录: |