gpt4 book ai didi

php - 如何在 PHP 中通过 PDO 循环遍历 MySQL 查询?

转载 作者:IT老高 更新时间:2023-10-28 23:45:34 25 4
gpt4 key购买 nike

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

显然,“其他东西”将是动态的。

最佳答案

这是一个使用 PDO 连接到数据库的示例,告诉它抛出异常而不是 php 错误(将有助于您的调试),以及使用参数化语句而不是自己将动态值替换到查询中(强烈推荐):

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");

// 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 placeholders 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();
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
}

关于php - 如何在 PHP 中通过 PDO 循环遍历 MySQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/159924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com