PDO对象出问题

时间:2014-01-16 17:53:01

标签: php mysql pdo

所以我创建了一个会员网站到目前为止我只有2个类用于连接数据库和用于管理用户的类

这是数据库的类:

class dbConnect
{
  protected $db_conn;
  public $db_host = '127.0.0.1';
  public $db_user = 'root';
  public $db_pass = '';
  public $db_name = 'db';

  public function connect()
  {
    try
    {
      $this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user,$this->db_pass);
      return $this->db_conn;
    }
    catch(PDOException $e) 
    {
      return $e->getMessage();
    }
  }

}

这是用户类,它只有1个方法我刚开始这个项目

class ManageUsers
{
  public $link;

  function __construct()
  {
    $db_connection = new dbConnect();
    $this->link = $db_connection->connect();
    return $this->link;
  }

  function registerUsers($username,$email,$password,$ip_adress,$date)
  {
    $query = $this->link->prepare("INSERT INTO `users` (username,email,password,ip_adress,date_joined) VALUES(?,?,?,?,?)");
    $values = [$username,$email,$password,$ip_adress,$date];
    $query->execute($values);
    $confirm = $query->rowCount();
    return $confirm;
  }
}

现在我只是运行一个测试对象来查看是否所有这些功能

$test = new ManageUsers();
echo $test->registerUsers('bob','a@a.com','lol','127.0.0.1','2012');

现在我收到错误,我正在调用非对象的prepare语句。说实话,我不明白,因为我在构造方法中创建了对象。以及任何建议有帮助谢谢!

2 个答案:

答案 0 :(得分:3)

我认为PDO对象无效,因为你在对象的方法/属性中使用双引号,在这种情况下你需要使用复杂的字符串表示法("{$object->property}")或用.连接字符串(a点)

about php strings

$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user,$this->db_pass);

更改为:

$this->db_conn = new PDO("mysql:host={$this->db_host};dbname={$this->db_name}", $this->db_user,$this->db_pass);

答案 1 :(得分:1)

我在这里有一个非常类似的剧本

class dbConnect
{
  protected $db_conn;
  public $db_host = '127.0.0.1';
  public $db_user = 'root';
  public $db_pass = 'roadmin';
  public $db_name = 'todo';

  public function connect()
  {
    try
    {
      $this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user,$this->db_pass);
      return $this->db_conn;
    }
    catch(PDOException $e) 
    {
      return $e->getMessage();
    }
  }

}

class ManageUsers
{
  public $link;

  function __construct()
  {
    $db_connection = new dbConnect();
    $this->link = $db_connection->connect();
    return $this->link;
  }

  function registerUsers($username,$email,$password,$ip_adress,$date)
  {
    $query = $this->link->prepare("INSERT INTO `users` (username,email, password, ip_adress, date_joined)  VALUES(?,?,?,?,?)");
    $values = [$username,$email,$password,$ip_adress,$date];
    $query->execute($values);
    $confirm = $query->rowCount();
    return $confirm;
  }

  function loginUser()
  {

  }
}

$test = new ManageUsers();
echo $test->registerUsers('bob','a@a.com','lol','127.0.0.1','2012');