如何在 PHP 中通过 PDO 循环执行 MySQL 查询?
我正在慢慢地将所有 LAMP 网站从 mysql_ 函数迁移到 PDO 函数,但我遇到了第一堵墙。 我不知道如何使用参数循环结果。 我对以下内容很满意:
foreach ($database->query("SELECT * FROM widgets") as $results)
{
echo $results["widget_name"];
}
但是,如果我想做这样的事情:
foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
echo $results["widget_name"];
}
显然“其他东西”将是动态的。
I'm slowly moving all of my LAMP websites from mysql_ functions to PDO functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:
foreach ($database->query("SELECT * FROM widgets") as $results)
{
echo $results["widget_name"];
}
However if I want to do something like this:
foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
echo $results["widget_name"];
}
Obviously the 'something else' will be dynamic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一个使用 PDO 连接到数据库的示例,告诉它抛出异常而不是 php 错误(将有助于您的调试),并使用参数化语句而不是自己将动态值替换到查询中(强烈推荐):
Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):
根据 PHP 文档 说你应该能够做到下列:
According to the PHP documentation is says you should be able to to do the following:
如果你喜欢 foreach 语法,你可以使用下面的类:
}
然后使用它:
If you like the foreach syntax, you can use the following class:
}
Then to use it: