How to get last inserted id from table MySQL [duplicate] - php

This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Last inserted id from specific table
(8 answers)
Closed 5 years ago.
I am running 1 script in php for that I need last inserted id in subscription table. By using that id I want to make notification note for that subscription.
I used:
SELECT LAST_INSERT_ID() FROM subscription
I am getting 0 instead of real last inserted value.

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
Like this :
mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$last_id = mysql_insert_id();
See this : mysql_insert_id()

LAST_INSERT_ID() returns the last id from a previous insert statement. If you want the most recently inserted record and are using Auto Increment Prime keys, you can use the code below:
SELECT MAX( id ) FROM subscription;
If you need to know what the NEXT id will be, you can get this from INFORMATION_SCHEMA
SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'test'
mysql_insert_id

This question has already been answered many times: MySQL: LAST_INSERT_ID() returns 0
You are using that function out of context. It will only work if you inserted a row immediately prior thusly:
INSERT INTO 'subscription' (name) VALUES ('John Smith');
SELECT LAST_INSERT_ID() FROM subscription
You can however select the row with the highest id, which logically would be the most recently added...
SELECT MAX( id ) FROM subscription;
The standard approach however is to simply call mysqli_insert_id or mysql_insert_id (depending on whether you are using the mysqli or mysql PHP library. I should add that the mysql library is very inadvisable to use since it is almost completely deprecated). Here's what the whole thing would ideally look like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("INSERT INTO 'subscription' (name) VALUES ('John Smith');");
printf ("New Record has id %d.\n", $mysqli->insert_id);
//Output is something like: New Record has id 999
If however you didn't insert a subscription in the same script as collecting the most recent row ID, use the 'select max' approach. This seems unlikely given that you mentioned '1 script'
Also, if your ID's are non-consecutive, or you do not have an ID field, or you have row ID's higher than the one you just added you should probably consider a 'date_added' column to determine which one was really the latest. These scenarios are rather unlikely however.

this is the better approach 2 and 3 works but MAX(id) take more time to execute.
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'dbName' AND TABLE_NAME = 'tableName';
SELECT tableName.id FROM tableName ORDER BY tableName.id DESC LIMIT 0,1;
SELECT MAX( id ) FROM tableName;

This will always give you the maximum id, which says the biggest number is the last inserted one
SELECT MAX(id) as MaximumID FROM subscription;

$last_id=mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 0 , 1" );
$row=mysql_fetch_assoc($last_id);
echo $row['id'];
Replace id by your id field name in database and table_name by your table name.

Related

how to show last inserted record id from mysql database on live site?

I want to show highest record id from mysql database on live. I am using following code and it's working on localhost but not on live site.
<?php
$q ="SELECT LAST_INSERT_ID()";
$result = mysqli_query($q);
$data = mysqli_fetch_array($result);
echo $data[0];
?>
As Jon mentioned you need to add MAX(). So did you setup your live database exactly the same as the localhost one? Maybe tell us the error?
(Can't comment yet, sorry)
use sub select query if id is unique.
select row
from table
where id=(
select max(id) from table
)
if id is not unique then use this.
select row from table ORDER BY id DESC LIMIT 1
you can use id column if you are using as PK and auto increment.
Select * from TABLE order BY id DECS LIMIT 1
if you are talking about concurrent queries then i have done something different to tackle this situation.
insert a timestamp in a new column and then fetch the same
please check the below code
$token= data();
insert into TABLE ('val1', 'val2', $token);
and then
you can user $token to get id of last inserted row by something like this
Select * from TABLE where token = $token

Unable to select highest value from a column

I have suffered with this for to long. It is turning me nuts...
I just want to take the max value of a column, add 1 to id and then insert a new entry.
The table has a column 'id' and lets say 'name' and 'age'
The problem is that the $new_id variable is not selecting the highest value from the id column. I know I am doing something wrong... but what??
Please help, I know this must be a pretty basic issue, but I have been looking at this for hours...
$relations_table="xxx_sobipro_relations";
$sql="SELECT * FROM '$relations_table' ORDER BY id DESC LIMIT 1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
$new_id = $row[id] + 1;
//more code
$query="INSERT INTO $relations_table (id, pid, oType, position, validSince)
VALUES ($new_id, 2, 'testtest' , $position , NOW() )";
Use this instead:
SELECT COALESCE(MAX(id)+1,0) FROM `$object_table`
SELECT * FROM `$object_table`
table names and field names not in '' but `` (backticks)
And you should ask the database for errors...
and you should NOT use the mysql extension anymore, but switch to mysqli or PDO...
You should look into AUTO_INCREMENT - turning that on for your id column will cause it to increase by one automatically every time you insert a row. That way, you won't have to specify id when you do the insertion, because MySQL keeps track of it for you.
You can do this on your insert:
$query="INSERT INTO $relations_table (id, pid, oType, position, validSince)
VALUES ((SELECT MAX(id)+1 FROM $object_table), 2, 'testtest' , $position , NOW() )";
Auto_increment is a better option, but this will work when you can't auto_increment.
First, it's $row['id'] not $row[id].
Second, mysql_* is deprecated, do not use it. Instead use PDO or mysqli.
Third, you can use MAX to get maximum value from column. SELECT MAX(id) FROM '$object_table' LIMIT 1.
And most important, set id field to autoincrement and don't set it (MySQL will do it).
So, the query you're looking for is:
SELECT MAX(id) FROM table
But many databases provide an "auto-increment" functionality where you can specify a column (in this case id) to be the primary key and have its value auto-increment, so you don't have to do any of this.

Selecting the most recently added record to the database in Mysql [duplicate]

This question already has answers here:
PostgreSQL, SELECT from max id
(5 answers)
Closed 4 years ago.
I have a table in database which has a primary key called id. Now i want to display the most recently added 2 records into the table.
Assuming id is some sort of auto-incrementing integer value then the following will work
SELECT * FROM table ORDER BY id DESC LIMIT 2;
If you want just the last inserted record id (again assuming the insert generates an autoincrement id) there is also LAST_INSERT_ID. But beware this is global and will return last inserted id database-wide so it is not often used in SELECTS but rather as an OUT paramer in a routine to return the id of the just-inserted row.
SELECT LAST_INSERT_ID();
This wil definitely work,
SELECT * FROM table_name ORDER BY id DESC,LIMIT 2.
Try,
SELECT * FROM `table`
ORDER BY id
DESC
LIMIT 0, 2;

How to recive the last row id in the database?

How to receive the last row id in the database without generating a new row or updating the row.
Just to read the last id?
I have the function mysql_insert_id and need something like this, but without generating a new row.
SELECT MAX(id) AS latest_id
FROM table_name
If you instead want the comming (and not yet existing) id without inserting a row, see my previous answer.
You need to use max() function like
select max(yourcol) from yourtable
You can try lot of queries for that :-
select * from TABLE_NAME order by ID desc limit 1;
"or"
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);

Discover last insert ID of autoincrement column in MySQL

I'm currently using:
SELECT MAX(id) FROM table
To discover the current id of a certain table, but i heard this can bring bad results. What is the proper way of doing that? Please, notice that i'm not INSERTING or DELETING anything before that query. I just want to know the current ID, without prior INSERT or DELETE.
Perform the following SQL:
SHOW TABLE STATUS LIKE 'TABLENAME'
Then check field AUTO_INCREMENT
You can use the following query:
SELECT id FROM table ORDER BY id DESC LIMIT 1;

Categories