我总是为我的PDO查询语句使用相同的变量,例如:
// Query 1
$stmt = $db->prepare("UPDATE table_1 SET name=? WHERE somthing=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->bindValue(2, $something, PDO::PARAM_STR);
$stmt->execute();
// Query 2 (right after the above)
$stmt = $db->prepare("UPDATE table_2 SET another_column=? WHERE id=?");
$stmt->bindValue(1, $another_column, PDO::PARAM_STR);
$stmt->bindValue(2, $id, PDO::PARAM_INT);
$stmt->execute();
我知道这是ok的第一行($stmt = $db->...)
,我的疑问是关于绑定值。例如,如果我忘记在第一个查询中绑定一些东西,我的查询是否会在第二个查询中使用下一个绑定(反之亦然)?还是在execute()
之后一切都重置?
哪一个是更好的实践?
- 使用相同的变量避免错误(例如总是$stmt)
- 使用不同的变量
使用不同的变量使调试更容易,但我偶尔这样做,因为更容易键入提示单个语句。
我的疑问是关于绑定值。
每个db->prepare()
返回一个全新的'PDOStatement
,所以没有绑定值的问题。
在这种情况下,在同一作用域中使用不同的语句,我为语句选择更具体的名称。
所以在你的例子中,我将它们命名为$stmtUpdTable1
和$stmtUpdTable2
或类似的东西。
因为我不能评论其他答案:我认为没有必要取消不再使用的变量,垃圾收集器将完成他的工作。不需要使代码混乱
我更愿意在每次查询后取消设置$stmt
。这样我就不用担心你上面提到的那些事情了。
// Query 1
$stmt = $db->prepare("UPDATE table_1 SET name=? WHERE somthing=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->bindValue(2, $something, PDO::PARAM_STR);
$stmt->execute();
unset($stmt);
// Query 2 (right after the above)
$stmt = $db->prepare("UPDATE table_2 SET another_column=? WHERE id=?");
$stmt->bindValue(1, $another_column, PDO::PARAM_STR);
$stmt->bindValue(2, $id, PDO::PARAM_INT);
$stmt->execute();