php - 返回 ROW 以及使用 PDO 循环遍历 ROWS 的最简单方法是什么?

标签 php mysql prepared-statement

如果我正在做一个旧的查询来返回一行,我会做这样的事情:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);

echo $row['id'];

我如何使用准备好的语句来做到这一点?我能做到这一点...

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to pull out this one row?       

 }

其次,如果我有多行,我会这样做:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {

   echo $row['id'];

}

同样,通过 PDO,我可以到达类似的地方......

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to loop through the rows??
    //
    // something like this...?
    //
    while ($row = $stmt->fetch()) {
       echo $row['id'];
    }       

 }

最佳答案

假设您已连接到数据库并且 $dbh 是您的 PDO 对象。

<?php

$email = 'myEmail@somesite.com';

$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");

$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);

$stmt->execute();


/* One row. */
$result = $stmt->fetch();

if ($result !== FALSE) {
    $stmt->closeCursor();

    echo $result['id'];
}


/* Multiple rows. */
$result = $stmt->fetchAll();

if ($result !== FALSE) {
    foreach ($result as $row) {
        echo $row['id'];
    }
}

?>

关于php - 返回 ROW 以及使用 PDO 循环遍历 ROWS 的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723612/

相关文章:

php - 永久链接策略(不是 wordpress)

php - 在 PHP 中解析 libconfig 文件

MySQL 8递归CTE生成行数

php - Wordpress 无法连接到非常小的站点中的 DB : Too Many Connections,

没有 PDO 的 MySQL 的 PHP ORM

php - 如何在 Phpmyadmin 上链接数据

php - MySQL 查询 - 将字符串与集合类型进行比较

java - JDBC mysql不支持PreparedStatement中的LIMIT占位符?

php - mysqli 对象没有方法执行

postgresql - 将 Oracle upsert 转换为 PostgreSQL 准备好的语句