php mysql_fetch_assoc() 的 PDO 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16363794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDO method for mysql_fetch_assoc()?
提问by donparalias
I used to do :
我曾经做过 :
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
I read that mysql statements are all deprecated and should not be used.
我读到 mysql 语句都已弃用,不应使用。
How can i do this with PDO?
我怎样才能用 PDO 做到这一点?
The first line would be :
第一行是:
$stmt = $db->prepare("SELECT * FROM table WHERE id = " . $id); // there was an aditional double quote in here.
$stmt->execute(array(':id' => $id));
What about the mysql_fetch_assoc() function?
mysql_fetch_assoc() 函数呢?
I am using php
我正在使用 php
回答by Willy Pt
You can use (PDO::FETCH_ASSOC)
constant
Usage will be
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
....
}
Here's the reference (documentation precisely) : http://www.php.net/manual/en/pdostatement.fetch.php
您可以使用(PDO::FETCH_ASSOC)
常量
用法将是
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
....
}
这里的参考(文档准确):http: //www.php.net/manual/en/pdostatement.fetch.php
回答by Tymoteusz Paul
All well documentned in the manual: http://php.net/manual/en/pdostatement.fetchall.php
手册中有详细记录:http: //php.net/manual/en/pdostatement.fetchall.php
As example:
例如:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
回答by Your Common Sense
There is a nice manual right here.
有一个很好的手册就在这里。
From which you can learn what you don't need to set fetch mode explicitly with every fetch.
...and even what with PDO you don't need no arrays at all to echo a number:
您可以从中了解不需要在每次获取时显式设置获取模式的内容。
...即使使用 PDO,您也根本不需要数组来回显数字:
$stmt = $db->prepare("SELECT number FROM table WHERE id = ?");
$stmt->execute(array($id));
echo "Hello User, your number is".$stmt->fetchColumn();
回答by Mehdi Karamosly
This is a nice tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
这是一个不错的教程:http: //wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query("SELECT * FROM table");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($results);
?>
回答by rational-space
You can use PDO::FETCH_ASSOC for the same.
您可以使用 PDO::FETCH_ASSOC 进行相同的操作。
$stmt = $db->prepare("SELECT * FROM table WHERE id = :id");
$stmt->execute(array(':id' => $id));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
while($record = $stmt->fetch()) {
//do something
}
You can find a good tutorial here
你可以在这里找到一个很好的教程