简体   繁体   中英

Return row ID from MySQL insert

I have this function inside a functions file. I call it using this (from another file that calls includes the functions file): newBorrow_request($newBorrowRequest); ($newBorrowRequest) is an array of fields.

The function inserts data into the database, and it works fine.

The question: How can i return the ID field that it inserts into? I need the value in the same file where the function is called, can someone give me code for the function & code of how to call it in another file to get the ID?

Thanks

function newBorrow_request($newBorrowRequest) {
array_walk($newBorrowRequest, 'array_sanitise');

$fields = '`' . implode('`, `', array_keys($newBorrowRequest)) . '`';
$data = '\'' . implode('\', \'', $newBorrowRequest) . '\'';

$query = mysql_query("INSERT INTO `borrowRequest` ($fields) VALUES ($data)");
if (!$query) {
    die('Could not query:' . mysql_error());
}

} 

The question isn't just about how to get the last insert id, it's also about how to get it outside of the function.

It needs to be returned by the function.

function newBorrow_request($newBorrowRequest){
    // your procedure
    return mysql_insert_id();
}

When you call the function, the return sets the variable

$last_insert_id=newBorrow_request($some_data);

which you can use

echo $last_insert_id;

NB. Please use mysqli or PDO instead of mysql

You could use this line of code:

printf("Last inserted record has id %d\n", mysql_insert_id());

But be aware this function is deprecated as of php 5.5.0. If you look at php.net/mysql_insert_id a few suggestions are given for replacements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM