我开始使用 PDO 并使用 PDO 成功连接到 MySQL。但是,当我尝试从数据库中选择内容时,什么也没有发生。没有任何回声。 (即使我在该表中有记录,并且列 username 存在)我的 PHP 日志中没有错误。
我正在使用 MAMP 并且所有 PDO 组件似乎都在 phpinfo() 中工作(因为我首先能够连接到数据库)
请让我知道可能出了什么问题。多谢
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
您需要告诉 PDO 您希望它抛出异常:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
根据您在下面的评论,很明显您的 DSN 不正确。它应该是:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
请注意,语法是dbname=
而不是dbname:
(你原来有)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)