看来我可以使用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 Object()bool(false) 致命错误:在第32行的Database.php中调用非对象的成员函数fetch()
所以基本上,$ link作为PDO对象返回(我更改了我的用户名和密码以查看是否捕获了异常;它是)并且PDOConnection :: Query由于某种原因返回null。这是我第一次与PDO打交道 - 我做的有趣吗?
答案 0 :(得分:0)
查询很可能失败,您确定表mt3_users
的名称并且您选择了正确的数据库吗?该错误消息显示$result
不是对象,而是由于查询中的错误。
此外:
$row = $result->fetch($result);
应该是
$row = $result->fetch();
除非您要为fetch()
指定选项,否则您不会将对象作为参数传递。
答案 1 :(得分:0)
你可以尝试一下吗
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$rows = $pdolink->query("select * from mt3_users");
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
如果您需要坚持fetchAll
功能
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$q = $pdolink->prepare("select * from mt3_users");
$q->exectue();
$rows = $q->fetchAll();
var_dump($rows);
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
答案 2 :(得分:0)
数组([0] => 00000 [1] => 1046 [2] =>未选择数据库)数组()
没关系,我想。事实证明,在使用常规MySQL函数进行迁移时,我没有设置$ this-> sName($ this-> sName为null。我很惊讶它没有抛出异常。只有一半,虽然)
固定。
但是谢谢你们的答案:)
答案 3 :(得分:0)
为了在您的查询中收到错误:
$result = $link->query(...);
if($result===FALSE){
print_r( $link->errorInfo);
exit();
}
// the correct way to fetch one row
$link->fetch(PDO::FETCH_ASSOC); // or whatever way you want to fetch data