如何在PHP中通过PDO遍历MySQL查询? [英] How do I loop through a MySQL query via PDO in PHP?
问题描述
我正在将所有LAMP websites
从mysql_
函数移到PDO
函数,并且碰到了我的第一个砖墙.我不知道如何通过参数遍历结果.我可以满足以下条件:
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.
推荐答案
以下是使用PDO连接到数据库,告诉它引发Exception(而不是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):
// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);
// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password", $attrs);
// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare the statement. the place holders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");
// bind the parameters
$stmt->bindValue(":productTypeId", 6);
$stmt->bindValue(":brand", "Slurm");
// initialise an array for the results
$products = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
}
}
// set PDO to null in order to close the connection
$pdo = null;
这篇关于如何在PHP中通过PDO遍历MySQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!