Search code examples
phppdoexecprepare

In PDO, I can exec() a string, but not prepare() and then execute() it


If I PDO::exec() a query, it works. However, when I try to first PDO::prepare() then PDO::execute(), it does not work. Why?

For instance, this works as expected:

$db->exec($string);

This does not, though:

$stmt = $db->prepare($string);
$stmt->execute();

There are no errors thrown, and $db->errorInfo is showing all zeroes, meaning success.

This makes absolutely ZERO sense to me.

EDIT for Context:

Note, newDB() is just a function which initiates the DB with the settings I need here.

When I run the following, it works as expected:

$db = newDB();

if (!$error) {
    if (isset($id)) {
        try {
            $db->exec('UPDATE Events SET Title = "WHY" , Date = "2012-11-01 00:00:00", Place = "no", Description = "no", UDate = now() WHERE Id = "12"');
        } catch(PDOException $e) {
            $error = 1;
        }
    }
}

$db = null;

However, this does not and I do not know why:

$db = newDB();

if (!$error) {
    if (isset($id)) {    
        try {
            $stmt = $db->prepare('UPDATE Events SET Title = "WHY" , Date = "2012-11-01 00:00:00", Place = "no", Description = "no", UDate = now() WHERE Id = "12"');
            $stmt->execute();
        } catch(PDOException $e){
            $error = 1;
        }
    }
}

$db = null;

Solution

  • Have you set the exception mode ?

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