如何在PHP中通过PDO循环访问MySQL查询?

2022-08-30 14:08:35

我正在慢慢地将我所有的职能转移到另一个职能,我已经碰到了我的第一堵砖墙。我不知道如何使用参数遍历结果。我对以下内容很好:LAMP websitesmysql_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"];
}

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


答案 1

下面是一个示例,用于使用 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;
}

答案 2

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

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

推荐