我在PHP中有这个错误:
致命错误:在第21行的C:''examplep''examplep''htdocs''BookStore''user.php中的非对象上调用成员函数prepare()
这是我连接到数据库的连接类:
<?php
class Connection
{
public function dbConnect()
{
return new PDO("mysql:host=localhost; dbname=msm41","root","");
}
}
?>
这是我尝试检查登录内容的用户类:
<?php
include_once('connection.php');
class User
{
private $db;
public function construct()
{//just like c# creating an object of the connection class
//and calling the connection function.connection is return by calling
//dbConnect.
$this->db=new connection();
$this->db=$this->db->dbConnect();
}
//------------------------------login-------------------------------------------
public function Login($id,$pass)
{
if(!empty($id)&&!empty($pass))
{
//parameter query
$st=$this->db->prepare("select * from customers where C_ID=? and C_PWD=?");
$st->bindParam(1,$id);
$st->bindParam(2,$pass);
$st->execute();
if($st->rowCount()==1)
{
echo"acces granted";
}
else
{
echo"incorect username or password";
}
}
else
{
echo"please enter your id and a password";
}
}
//----------------------------login----------------------------------------------
}
?>
我一直在搜索,发现很多人都有同样的错误。我所理解的是,也许我的PDO不可见,但我不认为是这样,因为我正在返回并保存那个PDO对象。
$this->db被设置为Connection
对象,该对象只有一个dbConnect()
方法。此外,construct()
不是一个神奇的方法,不会在构造时自动调用。__construct()
就是您想要的。
为什么不创建一个新的PDO对象作为$this->db?加班是没有必要的。