I’m [finally] learning PDO, and I’ve been dealing for the past hour with a problem that I cannot seem to solve. I have this code:
//Simple script that connects to mysql and database.
$db = new PDO ("mysql:host=".Configuration::get('MysqlServername').";dbname=".Configuration::get('MysqlDatabase').";charset=UTF-8",
Configuration::get('MysqlUsername'),
Configuration::get('MysqlPassword')) or die ("Error connecting");
// To test why it doesn't work
$STH = $db->prepare("INSERT INTO htranslations (keyword, en, page, last) VALUES (?, ?, ?, NOW())") or die ("Error preparing");
$STH->bindValue(1, "New_test", PDO::PARAM_STR) or die ("Error binding 1");
$STH->bindValue(2, "New test", PDO::PARAM_STR) or die ("Error binding 2");
$STH->bindValue(3, $_SERVER['PHP_SELF'], PDO::PARAM_STR) or die ("Error binding 3");
$STH->execute() or die ("Error executing");
Note: The or die are set only as a temporary measure to test where the error is originated. This code is simply not working, and I cannot figure out why. Now, what I’ve tried:
-
When doing
var_dump($db);, I getobject(PDO)#1 (0) { }on my browser. I guess this is NOT what it’s supposed to be, but I have no idea and couldn’t find much online. Theor diestatement not being executed makes me think that this might be right. -
The error displayed is
Error executing. This means that the last query couldn’t be executed, but that doesn’t help much since it could be a problem originated previously. -
The Configuration class is returning the right values. It was working previously with mysql and I tested it to see if it returned the right values (it does).
-
I’m in 000webhost.com free account. From this forum post and this other there shouldn’t be any problem with the PDO here. Furthermore,
print_r(PDO::getAvailableDrivers());returns mysql, sqlite and sqlite2. -
The other way around, inserting the values in an array in the execute() statement, doesn’t work either.
The working previous mysql_* code was (it was escaped previously):
$sql="INSERT INTO htranslations (keyword, en, page, last) VALUES ('$Id', '$Text', '".$_SERVER['PHP_SELF']."', now())";
mysql_query($sql);
Can you see what I’m doing wrong? If not, can you at least point me in some direction to keep testing it? I followed mainly (but not only) this tutorial. Thank you so much.
Thanks to the user andrewsi I could solve my problem.
Basically, I had no idea where to look for mistakes, so I run this code
var_dump($STH->ErrorInfo());to find out what was the problem and then fix it. My resulting code was:It returned a duplicate key, and that’s when I realized that the code that worked (once) with old mysql_* didn’t work here only because of a mistake in the database.
But I learned how to check out errors in the PDO way (well, still need the try/catch block) and hope that someone coming to this question with a similar error will solve it with this answer.