I started learning PDO and im still a bit of a PHP novice. Im doing a project to increase my knowledge but im stuck at the first hurdle.
Im getting this error: Call to a
Get same error and couldn't fix with code written above.
Here is easy fix as in your code this is the problem why PDO Sending Error :
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
I am using PHP 5.5 and if someone have same error then he will need this
After $dns you need to add this where $this->dbname . ";";
Only this is how it will work for PHP 5.5 and Will not work with $this->dbname . "'";
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ";";
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
@papaja hit the nail right on the head. Your PDO connection failed, thus you do not have a PDO object to run the prepare method on.
Off the top of my head, I think you are missing the end quote on the $dsn string. You probably want to add the following after $this->dbname and before the semi-colon:
. "'"
That's a single quote wrapped in double quotes. I use the following syntax to create the DSN string:
"mysql:host=$this->HOST;dbname=$this->DATABASE"
Anyway, create a test file so that you know exactly what the problem is. The test file should look like this:
class TestDatabase{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
public function __construct(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
}
Note that we are not running the instantiation of the PDO object within a try catch block. While you would never ever do that in production, it will be useful for your test because it will throw a fatal exception containing all of the details of your connection.
Now instantiate the test class and proceed by debugging the errors you receive. Again, they will be more detailed than the previous error because it will be an uncaught PDO exception.