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

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

Related

Get the AUTO_INCREMENT value after inserting a new row

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

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...

Return newest row added in MySQL

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

How can I know if my mysql_query update didn't actually update anything?

I am doing an update to a table for a row that may not exist. If it doesn't exist, I need to do an insert. I was initially planning on knowing that I needed to do an insert based on a negative return value from the update statement, but it isn't returning anything negative.
How can I know that the update didn't do anything? Do another query seeing if anything is there? Or maybe a query before?
Thanks!
Use http://php.net/manual/en/function.mysql-affected-rows.php
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
If you're using mysqli instead of mysql (mysql was deprecated a long time ago), it's mysqli_affected_rows.
Simply mysql_affected_rows method is the way to find out the change in table in both case if table exist or not. However, for optimized code better to check first for table existence like:
$status = mysql_query("select * from table_name");
if($status==false){
echo "table don't exists";
}
else{
//do your stuff here
}

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