开发者

PDO Connection to DB issues

I need to know if PDO extension I wrote is valid both syntactically and semantically. I've been var_dumping() my connection variables and while the variables are being passed to the constructor (with correct values), I'm not able to actually fetch anything from my database.

I've researched the PDO class on the PHP manual and from what I've uncovered the class I'm using is nearly identical to the extension class given in the examples section of the wiki page.

Here's my code:

class DBConnector extends PDO
    {
        private $host;
        private $username;
        private $password;
        private $db;
        private $dns;

        public function __construct($host, $username, $password, $db)
        {
            $this->host = $host;
            $this->username开发者_运维知识库 = $username;
            $this->password = $password;
            $this->db = $db;

            $this->dns = "mysql:dbname=".$this->db.";host=".$host;
            $connection = parent::__construct($this->dns, $this->username, $this->password);

        }
    }

And here's a test query which returns an array with...nothing inside of it. There is data within the database, so obviously something isn't correct.

function testQuery()
{
    global $connection;

    $query = "
        SELECT * FROM users
    ";

    $stmt = $connection->prepare($query);

    $result = $stmt->fetchAll();


}

Am I doing something wrong?


Try this:

class DBConnector extends PDO
{
  private $connection;
  private $host;
  private $username;
  private $password;
  private $db;
  private $dns;

  public function __construct($host, $username, $password, $db)
  {
      $this->host = $host;
      $this->username = $username;
      $this->password = $password;
      $this->db = $db;
      $this->dns = "mysql:dbname=".$this->db.";host=".$host;
      $this->connection = parent::__construct($this->dns, $this->username, $this->password);
      $this->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  public function testQuery()
  {
      $query = "SELECT * FROM a";
      $stmt = $this->prepare($query);
      if($stmt->execute()){
          return $stmt->fetchAll();
      }
      return array();
  }
}

$tg = new DBConnector('localhost', 'root', '', 'test');
$t = $tg->testQuery();
print_r($t);

the $connection is local to the DBConnector::__construct and I don't see any global there. So it will not exist in your testQuery function. By moving your function to the class, and create a connection property, it is easy to use it.


You need to execute query.

function testQuery()
{
    global $connection;

    $query = "
        SELECT * FROM users
    ";

    $stmt = $connection->prepare($query);

    if($stmt->execute()){

       $result = $stmt->fetchAll();

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜