5

I'm trying to determine whether a database insert query was successful or not by checking the return value of execute(), but it seems to be returning 0 even though I can see the data has been inserted into the database. The table I'm adding data to has a primary key but it's not set to auto increment.

$result = db_insert('my_table')
                    ->fields(array(
                      'user_id' => $user_id,
                      'my_value' => $num,
                    ))
                    ->execute();
print_r($result); //Prints 0, even when successful

How can I check to see if the db_insert() was successful or not if I'm not using an auto increment primary key?

Many thanks

7

That makes sense - if you haven't got an auto-increment field on the table, then you already have the ID that you're inserting, so it would make no sense for an arbitrary column (or primary key, or whatever) value to be returned by PDO.

If the query fails it will throw an exception. That's the best (probably only) way to check that the insert was successful in your case, short of running a separate query.

try {
  db_insert('...')->execute();
  // No exception thrown; PDO thinks the record was inserted correctly.
}
catch (PDOException $e) {
  // Query failed; recover based on $e->getMessage()
}
  • Actually, I forced the query to fail and it threw an exception so this makes perfect sense. Many thanks for your help. – Dan Murfitt Aug 27 '13 at 16:13
  • I suppose the try clause should include only the final ->execute() part at least while developing the module. Otherwise if a PDOException error is raised due to another cause during db_insert() etc before ->execute(), that is too caught by the catch clause, which could confuse the developer. Just a note. – Masa Sakano Aug 6 '15 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.