I'm writing some code using PDO:

$str_insert_sql = 'INSERT INTO some_table (vid, container_cdn_uri, container_name, root_filename, filename_extension, is_default, time_added, original_width, original_height, remote_url_hash) VALUES (:vid, :container_cdn_uri, :container_name, :root_filename, :filename_extension, :is_default, :time_added, :original_width, :original_height, :remote_url_hash)';
$arr_insert = array(
        ':vid' => 999999,
        ':container_cdn_uri' => 'http://foo.com/bar',
        ':container_name' => 'foo_bar',
        ':root_filename' => 'root_filename',
        ':filename_extension' => ".jpg",
        ':is_default' => 1,
        ':time_added' => date('Y-m-d H:i:s'),
        ':original_width' => 1600,
        ':original_height' => 1200,
      ':remote_url_hash' => md5('http://domain.com/blah');
);
$stmt = $db->prepare($str_insert_sql); // should throw an exception if it fails?? TODO: test if it does

I'm hoping that the prepare statement will throw an exception if the prepare statement fails but I can't seem to make this happen. Can anyone offer a prepare statement that will fail? the docs don't describe what circumstances will cause this failure and I can't seem to make it happen.

    First off, you obviously need to

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    If you connect to a mysql dbms using CLI, MySQLWorkBench or similar and try

    PREPARE stmt FROM 'unprepareable statement';
    

    you will get

    mysql error message wrote:

    Error Code: 1064
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unprepareable statement' at line 1

    which leads me to believe that this should throw an exception. Since it doesn't (while trying $stmt->execute() does), it could be that PDO is actually emulating prepared statements. If you have access to PostGre you could try and see what happens. If you get an exception there while you don't with MySql, you could go on and try compiling PHP so that PDO will use mysqlnd and see if this helps (--with-pdo-mysql=mysqlnd)

    Or you could just go with the current behaviour where you get no exceptions on prepare and catch the error when you execute.

      Thanks Johanafm. Excellent information as ususal. Thanks especially for the tip about --with-pdo-mysql=mysqlnd.

      I tried a variety of 'unpreparable statements' and as you pointed out, prepare always seems to "work" -- or rather it doesn't ever return FALSE which is what the docs say it will do on failure. I think you are correct that PDO in my case is just emulating prepared statements.

      I suppose it's enough to just exec and catch the errors there. I just don't have the time to recompile PHP at the moment.

        2 years later

        I appreciate this post and your work.Well done...

          Write a Reply...