PHP/MySQL insert row then get 'id' - php

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.

$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();

As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php

I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.

An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.

Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0

I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();

Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}

Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Related

PHP - INSERT and save LAST_INSERT_ID() into a variable

I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php

Why wont this MySQL Query save

So I have this short script. Its not giving out any error but it will not save into the DB. After I run the script I check the DB and nothing is there.
The db only has two items. (id and fid) ID is set at INT 11 auto and fid is set at VARCHAR 64. Also, I am connecting to my DB just fine.
<?php
$con = mysqli_connect('####', '####', '####', '#####');
if (mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if (isset($_POST['submit'])) {
$fid = $_POST['fid'];
$query = mysqli_query($con, "SELECT * FROM fid where fid = '$fid'");
$row = mysqli_num_rows($query);
if ($row == 1) {
echo 'This Federal Tax ID is already in use.';
} else {
mysqli_query($con, "INSERT INTO `fid` (id, fid) VALUES ('', '$fid')");
}
}
?>
Based on your comment:
It's supposed to be an empty value so the ID auto increments everytime.
That's not how auto-increment works. Your code is explicitly telling the record to not have a value:
"INSERT INTO `fid` (id, fid) VALUES ('', '$fid')"
If the id column is required, this will expectedly fail. (It may also be failing based on the type. You're trying to insert a string, but an auto-increment column would be numeric...)
An auto-increment column doesn't need to be supplied an empty value. Just omit it entirely:
"INSERT INTO `fid` (fid) VALUES ('$fid')"
Additionally, this code is wide open to SQL injection. You're going to want to read up on that. In short, you should use prepared statements which bind to user-input values. Don't concatenate those user-input values directly into your code, that allows the user to inject their own code.
If you want to use AUTO you need to either NOT specify the value at all or else specify a 0 (or NULL if defined as NOT NULL):
Either
INSERT INTO fid (fid) VALUES ('$fid')
or
INSERT INTO fid (id, fid) VALUES (0, '$fid')
or (if id is defined as NOT NULL)
INSERT INTO fid (id, fid) VALUES (NULL, '$fid')
SOURCE: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Insert result into multiple tables

EDIT:
Im trying to submit a form with a title and body but i want the title to go to one table and body to go to another table, this in itself i can do but i need the ID generated from the title being inserted into its table to then be inserted into a field in the table the body is inserted so as to keep them linked.
What i have so far: I know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
if (#$_POST['post'])
{
$body = #$_POST['body'];
$title = #$_POST['title'];
$BoardID = #$_POST['BoardID'];
$MemberID = #$_POST['MemberID'];
$date = date("Y-m-d H:i:s");
include ('connect.php');
$insert = mysql_query("INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')");
if($insert) {
header("location: ?p=posts&thread=$Thread_ID");
exit();
}
}
I need to somehow get $Thread_ID which has been generated in the insert and add that to a second insert for adding body to the post table, if that makes sense.
I tried getting the latest $Thread_ID and adding +1 but if multiple threads are posted at once they might get crossed over.
How would i go about fixing this?
The PHP manual tell us:
This extension Mysql is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
(see ref.)
You must use mysqli or PDO, to make a connection between PHP and a MySQL database.
mysqli
If you want the id of the inserted row, you can use $mysqli->insert_id (ref)
Example:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
PDO
If you want the id of the inserted row, you can use $dbh->lastInsertId(); (ref)
And don't forget to sanatize all your inputs.
You need to execute both insert queries separately.
$insert = "INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')";
$result = #mysql_query($insert);
$Thread_ID=#mysql_insert_id();
$insert = "INSERT INTO posts VALUES ('','$BoardID',$Thread_ID','$body','$date','$MemberID')";
$result = #mysql_query($insert);
Thanks,

How to grab an auto incremented variable and insert it into an insert query

I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?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 words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php

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

Categories