How to access the row which has just been inserted into a DB with PHP/MySQL?
I have:
$sql = 'INSERT INTO `jos_db`.`jos_sections` (`id`, `name`) VALUES (NULL, \'foo\')';
mysql_query($sql, $dbi);
bar();
How do I access the new row in bar()?
If you 'id' column is an auto-increment, you can use mysql_insert_id :
Retrieves the ID generated for an
AUTO_INCREMENT column by the previous
INSERT query.
The example given in the manual looks like this :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
You can get the last item inserted with mysql_insert_id()
http://us.php.net/manual/en/function.mysql-insert-id.php
Use mysql_insert_id() function to select last row inserted in database.
SELECT rows from table where id = last_inserted_id
Using the PHP function mysql_insert_id() will return the id of the last row you inserted.
Related
How can I get the id that was just inserted for the current user if it is controlled by AUTO_INCREMENT?
(I need the Id for another use)
Note: some row can be deleted so MAX(id) is not an option.
Ex:
inserted row 2
inserted row 3
deleted row 3
inserted row 4 but MAX(id) returns 3..
Thank you very much!
With PDO:
$db->lastInsertId(); // $db is the PDO object
With MySQLi OOP:
$db->insert_id; // $db is the MySQLi object
With MySQLi procedural:
mysqli_insert_id($db); // $db is the connection variable
If you're using the old MySQL API, switch.
try
select ##identity
This should return the last value in the identity column
Since your answer is tagged with PHP, I'll answer in that context. If you're using the PDO API, you can use PDO::lastInsertId. If you're using the mysql function API, the equivalent would be mysqli_insert_id or mysql_insert_id.
Edit: Ninja'd :P
Use mysql_insert_id() or mysqli_insert_id()
you can use mysql_insert_id
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
EDIT:
mysql_insert_id is deprecated. now its mysqli_insert_id
In my PHP code, I save a record like this:-
mysqli_query($con, "INSERT INTO levels (levelName)
VALUES ('" . $_POST["levelName"][0] . "')");
And this works fine.
In the table 'levels', there is an auto-incrementing PK field called "ID". How would I go about returning/echoing the value of that field when the record is saved to the database?
Quoting from the following reference:
How to Get the Unique ID for the Last Inserted Row
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
# http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
-
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "INSERT INTO person VALUES ('Børge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();
mysql_close($con);
?>
from: http://www.w3schools.com/php/func_mysql_insert_id.asp
use
mysql_insert_id()
function
if using mysqli use something like this
$mysqli->insert_id
I was wondering what the code would look like to go into a table and then get the primary key in the last row that was added to the table.
How would you go across doing that I do not have a timestamp in the table for the rows in the database if that helps.
Purely MySQL solution:
SELECT LAST_INSERT_ID();
For PHP with pdo method
$lastId = $con->lastInsertId();
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
I have mysql data base in which i am adding data in mysql data base but problem is that it only stores only one record not more than that.
my table structure is
<?php
$con = mysql_connect("example.com","name","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("surveyipad", $con);
$response_id=$_POST['response_id'];
$participant_id=$_POST['participant_id'];
$question_id=$_POST['question_id'];
$answer_text=$_POST['answer_text'];
$answer_option=$_POST['answer_option'];
$query=("INSERT INTO survey_question_responses (response_id,participant_id,question_id,answer_text,answer_option)
VALUES ('', '$participant_id','$question_id','$answer_text','$answer_option')");
mysql_query($query,$con);
printf("Records inserted: %d\n", mysql_affected_rows());
echo($response_id)
?>
response id is primary key in table and also set to auto increment
Try like this
$query=("INSERT INTO survey_question_responses (participant_id,question_id,answer_text,answer_option)
VALUES ('$participant_id','$question_id','$answer_text','$answer_option')");
As you made the id field auto incremented don't insert it vie your INSERT query .
Write the query as
INSERT INTO survey_question_responses (participant_id, question_id, answer_text, answer_option)
VALUES ('$participant_id', '$question_id', '$answer_text', '$answer_option')
You should also explain or send the structure of your table.
This a bit looks complicated, i want to get the id column value of the processed query.
example:
$qu = mysql_query("INSERT INTO msgs (msg,stamp) VALUES('$v1','$v2')");
i want to get the ID of this query after storing the infos in database.
if it's impossible, is getting the last ID record and adding 1 will be safe and guaranteed?
Note: i use PHP and mySQL
Thanks
Here are the MySQL docs on this.
http://dev.mysql.com/doc/refman/5.1/en/getting-unique-id.html
If it's an auto_increment column, use the PHP function mysql_insert_id.
If you are using standard mysql in PHP, all you have to do, is to use mysql_insert_id() which takes resource $link as parameter (your mysql connection)
http://php.net/manual/en/function.mysql-insert-id.php
Basic usage:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('some product')");
echo 'Last inserted record has id of ' . mysql_insert_id();
?>
No, it is not safe to grab the highest id and just add 1 and use that as the new id. This is what's known as a race condition. If two queries attempt to do this operation at the same time, it could be that they both select the SAME highest id, both attempt to add 1, and then BOTH attempt to use the same id (which would be bad).
It's much better to use AUTO_INCREMENT fields as you're doing, and you can retrieve the inserted id in PHP as follows (from http://php.net/manual/en/function.mysql-insert-id.php):
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
Here's the code:
$qu = mysql_query("INSERT INTO msgs (msg,stamp) VALUES('$v1','$v2')");
$recent_id = mysql_insert_id();
The variable recent_id is what you are looking for.
Getting the last ID record and adding 1 MAY NOT be safe and IS NOT guaranteed. You are better off using the solution that I have indicated if you really want to play it safe.
Hope it helps.
Hope this helps:
int mysql_insert_id ([ resource $link_identifier ] )
http://us3.php.net/mysql_insert_id
check here if it`s not problem for you to use mysqli for php