Alex
Alex

Reputation: 9

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());
}

} 

Upvotes: 0

Views: 294

Answers (3)

Popnoodles
Popnoodles

Reputation: 28409

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

Upvotes: 1

Arthur
Arthur

Reputation: 931

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.

Upvotes: 0

Evan
Evan

Reputation: 63

If you're working with < 5.5.0: http://php.net/mysql_insert_id

Preferable: http://www.php.net/manual/en/mysqli.insert-id.php

Upvotes: 0

Related Questions