我有connection.php文件,我在$ db中初始化PDO。 我想检查在connection.php之后包含的User.php中的这个验证。 但它给了我错误。
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_host", $db_username,$db_password);
echo "PDO connection object created";
}
catch(PDOException $e){
echo $e->getMessage();
}
如何通过执行PDO验证此代码。 我将如何将PDO传递给用户类..
Fatal error: Call to a member function query() on a non-object in /var/www/youngib/rahul/yapi/user.php on line 41
$sql="select * from users where email='$this->email'";
$rs=$db->query($sql);
if(mysql_num_rows($rs)>0){
$msg=geterrormsg(4);
//email already exist
echo $msg= "{ 'success': 'false','msg':'$msg' ,'error_code':'4' }";
return false;
}
请帮助。
谢谢。
答案 0 :(得分:0)
将它注入到类中或创建像...一样的单例数据库类
注射:
class User
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function getDb()
{
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->execute(array(':email' => $email))->fetchColumn();
}
}
的Singleton:
class Database {
protected $pdo;
protected static $instance;
protected function __construct($dsn, $user, $password)
{
$this->pdo = new PDO($dsn, $user, $password);
}
public static function getInstance()
{
if(!self::$instance)
{
// normally you would load the dsn, user, and password from a config file
$db = Config::get('db');
self::$instance = new self($db['dsn'], $db['user'], $db['password']);
}
return self::$instance;
}
public function getDb()
{
return $this->pdo;
}
}
class User
{
protected $db;
public function __construct(PDO $db = null)
{
if(null !== $db)
{
$this->db = $db;
}
}
public function getDb()
{
if(!$this->db)
{
$this->db = Database::getInstance()->getDb();
}
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->exectute(array(':email' => $email))->fetchColumn();
}
}
答案 1 :(得分:0)
我讨厌这样说,但只想添加
global $db;
在$db->query($sql);
行之前。它可能会起作用,具体取决于$ db的创建位置。
也就是说,prodigitals的答案是一种大大改进的方法,它只涉及修复整个设计,这涉及更多的前期工作:)