Return newest row added in MySQL - php

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

Related

Returning values from saved row

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

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
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());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

Data in Mysql Table only store one record

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.

How do i get the SQL query ID after processing it?

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

Accessing last created row in PHP/MySQL

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.

Categories