$sql = new PDO('mysql:host=localhost;dbname=b','root','root');
$f = $sql->query('select * from user');
$sql->setFetchMode(PDO::FETCH_ASSOC);
while($row = $f->fetch()){
print_r($row);
}
输出是
Array
(
[id] => 1
[name] => turki
[mail] => ablaf
[pass] => 144
)
Array
(
[id] => 2
[name] => wrfwer
[mail] => fwerf
[pass] => werf
)
这就是我真正想要的.但是,如果我这样做
$sql = new PDO('mysql:host=localhost;dbname=b','root','root');
$f = $sql->query('select * from user');
$f->setFetchMode(PDO::FETCH_ASSOC);
print_r($f->fetch());
?>
输出是
Array
(
[id] => 1
[name] => turki
[mail] => ablaf
[pass] => 144
)
它有一个结果,但我在表中有两行;这是为什么?
解决方法:
应使用Fetch显示数据库结果的下一行
要获得所有行,您应该使用fetchAll();
将您的示例更改为:
$sql = new PDO('mysql:host=localhost;dbname=b','root','root');
$f = $sql->query('select * from user');
$f->setFetchMode(PDO::FETCH_ASSOC);
print_r($f->fetchAll());
?>
$sql = new PDO('mysql:host=localhost;dbname=b','root','root');
$f = $sql->query('select * from user');
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}
?>
标签:php,mysql,database,pdo
来源: https://codeday.me/bug/20190926/1819869.html