为什么我的PDO不起作用? [英] Why is my PDO not working?
问题描述
我开始使用PDO,并且已使用PDO成功连接到MySQL.但是,当我尝试从数据库中选择内容时,什么也没有发生.什么也没有回应. (即使我在该表中有记录,并且该列的用户名也存在)PHP日志中没有错误.
I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
我正在使用MAMP,并且所有PDO组件似乎都在phpinfo()中工作(因为我一开始就可以连接到db)
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
请让我知道可能出了什么问题.非常感谢
Please let me know what could have gone wrong. Thanks a lot
<?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您希望它引发异常:
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
在下面的评论中,很明显您的DSN不正确.应该是:
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
请注意,语法是dbname=
,而不是dbname:
(您最初使用的语法).
Note that the syntax is dbname=
rather than dbname:
(which you had originally).
这篇关于为什么我的PDO不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!