getInsertId

API Quick reference
Variable name: getInsertId
CMS versions: 0.9.x + Evo
Input parameters: ([resource conn_identifier])
Return if successful: AUTO_INCREMENT value from the last INSERT query.
Return type: int
Return on failure: 0 or false (see below)
Object parent:

API:DB:getInsertId

Description

integer getInsertId([resource conn_identifier $conn])

Get the atuomatically generated ID of the item that was just inserted into the database.

This function returns the AUTO_INCREMENT id of the last MySQL INSERT query. It will return 0 if there wasn't an AUTO_INCREMENT id created, and false if there is no link to a MySQL database. Since the returned value will be the id of the last query, you should call this function directly after your insertion query to ensure that the value is correct.

Usage

$newId = $modx->db->getInsertId();

Examples

This example function is passed two parameters: "$fields" and "$table". The function checks that "$fields" is an array, and if so it proceeds to insert the data into the database and return the "AUTO_INCREMENT" value. If the query fals, or if "$fields" is not an array, it returns false.

function insert_user( $fields, $table ) {
if( is_array( $fields ) {
if( $modx->db->insert( $table, $fields ) ) {
return $modx->db->getInsertId();
}
else {
return false;
}
}
else {
return false;
}
}

Example 2

$email = checkMail($_POST['email']);
$pass = makePass();
$sql = "INSERT INTO ".$modx->getFullTableName('web_users')." (username,password) VALUES ('".$email."', '".$pass."')";
$rs = $modx->db->query($sql);
$id = $modx->db->getInsertId();
$sql = "INSERT INTO ".$modx->getFullTableName('web_user_attributes')." (internalKey,email) VALUES (".$id.",'".$email."')";
$rs = $modx->db->query($sql);

In this case, we've used a simple registration form to get the email of a new member. First the returned POST value is checked through a function. A password is automatically generated with another function. These values are used as the username and password, and inserted into the web_users table.

The automatically generated ID for this new member is retrieved with the getInsertId function. The new member's ID is now used to insert the user's email into the "web_user_attributes" table.

This same value can then be used to insert the new member into a desired web group. This would be useful for registering a member to receive a newsletter, for example.

Related

[$modx->db->insert]()

Notes

It's worth noting that "mysql_insert_id()" (used by $modx->db->getInsertId()) returns an integer, so if you have a value larger than that (for example, a BIGINT), the value returned will be incorrect. In this case, you should use the last_insert_id() function instead.

Function Source

File: manager/includes/extenders/dbapi.mysql.class.inc.php
Line: 236

function getInsertId($conn=NULL) {
if(!is_resource($conn)) { $conn = $this->conn; }
return mysql_insert_id($conn);
}

Suggest an edit to this page.