如何在PHP中通过PDO遍历MySQL查询?

时间:2020-03-06 15:00:00  来源:igfitidea点击:

我正在将我所有的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"];
}

显然,"其他"是动态的。

解决方案

根据PHP文档的说法,我们应该能够执行以下操作:

$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $results)
{
   echo $results["widget_name"];
}

我不是专家,但这应该可行。

这是一个使用PDO连接到数据库,告诉它抛出Exception而不是php错误(将有助于调试),并使用参数化语句而不是将动态值替换为查询本身的示例(强烈建议):

// $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;