如果我正在做一个旧的查询来返回一行,我会做这样的事情:
$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/