如何在 PHP 中为动态查询构建参数化 PDO 语句?
如果已经有人问过这个问题,我们深表歉意。 我已经看到了有关静态 SQL 的答案,但在这种情况下,我想使用 PDO->prepare() 作为在运行时动态构建的查询字符串。
分解为一个简单的示例:
$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
if ($numberParams == 1) {
$TempSQL = $TempSQL . " field1 = '$val1' ";
} else {
$TempSQL = $TempSQL . " field2 = '$val2' ";
$TempSQL = $TempSQL . " AND field3 = '$val3' ";
}
db->query($TempSQL);
如何将其重写为 db->prepare()?
我是否也应该动态构建语句->execute(array(':param' => $var))) ?
有更好/更简洁的方法吗?
Apologies if this has been asked already. I've seen answers regarding static SQLs, but in this case I'd like to use PDO->prepare() for a query string that is built dynamically at runtime.
Breaking down into a simple example:
$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
if ($numberParams == 1) {
$TempSQL = $TempSQL . " field1 = '$val1' ";
} else {
$TempSQL = $TempSQL . " field2 = '$val2' ";
$TempSQL = $TempSQL . " AND field3 = '$val3' ";
}
db->query($TempSQL);
How do I rewrite this as a db->prepare()?
Should I build the statement->execute(array(':param' => $var))) on the fly as well?
Is there a better / neater way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许是这样的。 (未经测试)
Perhaps something like this. (untested)
根据您的示例,更简洁的方法是循环而不是切换。
db->prepare() 允许您使用 bindParam() 或 PDOStatement->exec()。 您可以使用? 来自示例 3 和 4,而不是命名字段值。
它仍然要求 SQL 语句已知所有字段。
Based on your example, a neater way would be a loop instead of switching.
db->prepare() allows you to replace patterns (on php.net, the example is putting a colon in front of the field name) using bindParam() or an array on the PDOStatement->exec(). You can use the ? from examples 3 and 4 instead of naming the field values.
It still requires that all the fields be known for the SQL statement.