0

I need to insert a row into a database using PDO. But it doesn't work and it doesn't print any errors so I don't know where the problem can be.

The connection is okay, because I can run UPDATE queries.

But on this query it gets stuck without printing any error:

$dbtype     = "mysql";
$dbhost     = "xxx";
$dbname     = "xxx";
$dbuser     = "xxx";
$dbpass     = "xxx";

$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO users (id, name) VALUES (:id,:name)";
$q = $db->prepare($sql);

$q->execute(array(
    ':id'=>$id,
    ':name'=>$name
));

Is there any other way to debug except this command?

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
halfer
  • 19,824
  • 17
  • 99
  • 186
JackDavis
  • 117
  • 1
  • 4
  • 17

2 Answers2

0

Probably you have error reporting turned off and you are not trying to catch an exception if your code throws one.

So you have to put your code into a try and catch block e.g.

try {
    //your stuff
} catch(PDOException $e) {
    echo $e->getMessage();
}

Because your PDO is set to throw an exception if an error occurred, so you have to catch that with this block. Also I would recommend you to turn on error reporting for useful error messages (Only while staging never in production).

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • Thank you, this return the error. But it is strange that `$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` dont work. I have enabled all warning and notices: `error_reporting(E_ALL); ini_set('display_errors', 1);` Okay, I will use this for debug, thanks. :) – JackDavis May 03 '15 at 17:57
  • @JackDavis Then it's probably not a fatal error and it doesn't get display from the error reporting only from catching the exception. – Rizier123 May 03 '15 at 18:00
  • this answer contradicts to itself. *IF* displaying errors is turned off, then there should be NO echo $e->getMessage(); as well – Your Common Sense Dec 24 '20 at 15:08
0

I had the same problem of not seeing any error messages from mysql. After research it appeared that the problem has got nothing to do with PHP itself, but with mysql server configuration. The default value of the variable lc_messages_dir pointed to non existing directory. After adding a line in mysqld.cnf, then restarted the mysql server, and finally it worked. For me the following was the right one:

lc_messages_dir=/usr/share/mysql

It is described in mysql reference manual: https://dev.mysql.com/doc/refman/5.7/en/error-message-language.html

Atanas Yordanov
  • 381
  • 3
  • 5