如何通过PHP中的PDO循环MySQL查询?

And*_*son 25 php mysql pdo

我正在慢慢地将我的所有功能LAMP websitesmysql_功能转移到PDO功能,我已经击中了我的第一个砖墙.我不知道如何使用参数循环结果.我很满意以下几点:

foreach ($database->query("SELECT * FROM widgets") as $results)
{
   echo $results["widget_name"];
}
Run Code Online (Sandbox Code Playgroud)

但是如果我想做这样的事情:

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

显然,"别的东西"将是动态的.

Sha*_*obe 67

下面是一个使用PDO连接到数据库的示例,告诉它抛出异常而不是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;
Run Code Online (Sandbox Code Playgroud)


Dar*_*ein 6

根据PHP文档说你应该能够做到以下几点:

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

我不是专家,但这应该有效.

  • @DGB,Darryl从原始问题的例子中得到的"别的东西".这个问题与动态组装查询无关,它与迭代查询结果有关.他回答得当.虽然我同意Shabbyrobe给了*更好的答案. (6认同)
  • 这并没有考虑逃避可能是动态的"别的东西".准备好的查询如Shabbyrobe所示就是答案. (3认同)
  • *"显然'别的'将是动态的."* (3认同)