user3100131
user3100131

Reputation: 11

How to do a PHP PDO insert

I'm trying to insert in to a database using PDO.

Here is my code:

$SQLinsert = $odb->prepare("INSERT INTO `sites` VALUES(NULL, :site, :username)");
$SQLinsert -> execute(array(':site' => $site, ':username' => $user));

I added the PDO error reporting and I get this error:

Array ( [0] => 00000 [1] => [2] => )

Upvotes: 0

Views: 125

Answers (2)

Imran
Imran

Reputation: 3072

You can use php try catch block with get_message() method.

  try{ 
        $SQLinsert = $odb -> prepare("INSERT INTO `sites` VALUES(NULL, :site, :username)");
        $SQLinsert -> execute(array(':site' => $site, ':username' => $user));
    } 
    catch(PDOException $exception){ 
        print  $exception->getMessage(); 
    } 

Or you need following attribute in your db connection

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

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33511

PDO doesn't give error messages when the SQL is wrong. You can use errorInfo to get SQL errors:

if ($SQLinsert -> execute(array(':site' => $site, ':username' => $user))) {
    // ok
} else {
    print_r($odb->errorInfo());
}

My guess on your SQL by the way is that you have more columns than those three. If that's the case, add the column names to make it work:

INSERT INTO `sites` (col1, site, username) VALUES(NULL, :site, :username)

Upvotes: 5

Related Questions