PHP 与PDO:可以连接DB;好像无法查询
看来我可以使用 PDO 连接到我的数据库,但无法用它执行任何查询。示例:
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
}
catch (PDOException $e) {
die ($e);
}
print_r($link);
$result = $link->query("select * from mt3_users");
var_dump($result);
$row = $result->fetch($result);
die("Your id is: ".$row["id"]);
//$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
if (!$link) {
echo "Failed to connect to $this->sHost!";
return false;
}
return $link;
}
这将返回以下内容:
PDO 对象 ( ) bool(false) 致命错误:在 Database.php 第 32 行的非对象上调用成员函数 fetch()
所以基本上,$link 作为 PDO 对象返回(我更改了用户名和密码以查看是否捕获了异常;是的)并且 PDOConnection::Query 由于某种原因返回 null。这是我第一次处理 PDO——我是在做一些有趣的事情吗?
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
}
catch (PDOException $e) {
die ($e);
}
print_r($link);
$result = $link->query("select * from mt3_users");
var_dump($result);
$row = $result->fetch($result);
die("Your id is: ".$row["id"]);
//$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
if (!$link) {
echo "Failed to connect to $this->sHost!";
return false;
}
return $link;
}
This returns the following:
PDO Object ( ) bool(false)
Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32
So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查询很可能会失败,您确定表
mt3_users
的名称以及您是否选择了正确的数据库?该错误消息显示$result
不是对象,这是由于查询中的错误造成的。另外:
应该是,
除非您想为
fetch()
指定选项,但不将对象作为参数传递。Most likely the query fails, are you sure of the name of the table
mt3_users
and that you have selected the right database? That error message shows that$result
is not an object and that's due to an error in the query.Also:
should be
unless you want to specify options to
fetch()
, but you don't pass the object as argument.Array ( [0] => 00000 [1] => 1046 [2] => 未选择数据库 ) Array ( )
没关系,我想。事实证明,在从使用常规 MySQL 函数迁移时,我没有设置 $this->sName ($this->sName 为 null。我很惊讶它没有抛出异常。不过,只有一半)
固定的。
不过还是谢谢你们的回答:)
Array ( [0] => 00000 [1] => 1046 [2] => No database selected ) Array ( )
Nevermind, I guess. It turns out that while migrating from using regular MySQL functions, I wasn't setting $this->sName ($this->sName was null. I'm half surprised it didn't throw an exception. Only half, though)
Fixed.
But thank you guys for the answers :)
您可以尝试一下吗
?如果您需要坚持使用
fetchAll
函数can you give this a try
and if you need to stick with
fetchAll
function为了得到查询中的错误:
In order to get the error in your query: