MYSQL: SQL query to get value of autoincrement field
I have a table. Primary key id
and its automatic increase. Now when I insert a new record, I need to get the id with which the record was updated. How can i do this? If I use query ...
select max(id) from table_name
... after execution I can get the id. But can I be sure that its the ID of the newly inserted record? Because many people will be using the app at the same time.
I am using php and mysql.
Can ayone prove me an example of a code snippet in php with mysql?
source to share
If you want to know what is the new id from the auto increment column, you just need to run mysql_insert_id()
right after your insert request.
Same:
//--connection already made to database
//--now run your INSERT query on the table
mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");
//-- right after that previous query, you run this
$newest_id = mysql_insert_id();
And $newest_id
will now contain the id of the last inserted row.
source to share
you can use this to get the next auto_increment value (given that you have already connected to the server and selected db;
$query = "SHOW TABLE STATUS LIKE 'tbl_name'";
$result = mysql_query($query);
$auto_incr_val = mysql_result($result, 0, 'Auto_increment');
echo $auto_incr_val;
This will give you the value to be used further in the auto_increment column. EDIT: I'm sorry .. That wasn't your question ....
source to share