PDO Connect to DB Errors

I need to know if the PDO extension I wrote is both syntactically and semantically. I was var_dumping () my connection variables, and although the variables are passed to the constructor (with the correct values), I cannot extract anything from my database.

I studied the PDO class in the PHP manual, and from what I found, the class I use is almost identical to the extension class specified in the examples section of the wiki page.

Here is 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 is a test request that returns an array with ... nothing inside it. There is data in the database, so obviously something is wrong.

 function testQuery() { global $connection; $query = " SELECT * FROM users "; $stmt = $connection->prepare($query); $result = $stmt->fetchAll(); } 

Am I doing something wrong?

+6
source share
2 answers

Try the following:

 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); 

$ connection is local to the DBConnector :: __ construct, and I don't see any global there. Thus, it will not exist in your testQuery function. Moving your function to a class and creating a join property is easy to use.

+11
source

You need to complete the request.

 function testQuery() { global $connection; $query = " SELECT * FROM users "; $stmt = $connection->prepare($query); if($stmt->execute()){ $result = $stmt->fetchAll(); } } 
+3
source

Source: https://habr.com/ru/post/897578/


All Articles