->insert() – Insert current objects variables into database


mixed $DB_DataObject->insert ( )


Insert the data into the database, based on the variable values of the current object and returns the ID of the inserted element if sequences or primary keys are being used. The values are correctly quoted, and some limited type checking is done.

With mysql, the mysql_next_id() method is used, on other databases, PEAR DB sequence method is used.

Note, insert() may not return the ID correctly in quite a few situations:

  • If the database backend does not support it.
  • The generator did not correctly flag the correct column as autoincrement/nextval
  • An error occured (turn on debugging to see it)
  • The insert failed or '0' rows where affected.

Return value

mixed - Id or key


Possible PEAR_Error values
Error code Error message Meaning Solution
DB_DATAOBJECT_ERROR_INVALIDCONFIG "insert:No table definition for $table"    
DB_DATAOBJECT_ERROR_NODATA "insert: No Data specifed for query"    
DB_* * see PEAR::DB see PEAR::DB


This function can not be called statically.


Simple insert

= new DataObjects_Person;
$id $person->insert();

Resulting SQL

(nameVALUES ('fred');
Perform a select count() request (Previous) Update objects variables into database (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

Note by: del@babel.com.au
Here is how to fetch the error message:

$my_id = $my_object->insert();
if ($my_id) {
debug("I just inserted record ID " . $my_id);
} else {
$error = &PEAR::getStaticProperty('DB_DataObject','lastError');
$debug("DB_DataObject Error: " . $error->getMessage() );
Note by: nailz420@gmail.com
Is there a way to get the database error code and message? For example, I would like to be able to check for error code 1062 on duplicate key error in a mysql db. Where would that value be stored?
Note by: Charlie Shin
I spent at least 3 days to find out why there is extra table with additional "_seq" in my database. I finally realize it is created because sequenceKey(). I don't know why bother to find sequenceKey() if my table is no need sequence key? This feature should not set by flag or option, otherwise I have to manually add in return array(false, false) each time after if package upgrade?
Note by: pierre2543@hotmail.com
By default insert() will populate key fields automatically. If you want to manage your own keys, override sequenceKey() in your DO as follows:

function sequenceKey(){
return array(false,false);