How to get the last inserted id in PHP - php

Here I am trying to get the inserted id from MySQL database in the table I have product_id. After insert I want to get the latest inserted product_id and store it in array ['newid'][]
The insert query is going on pretty good, but I am not able to get the product_id in to the array. when I print the array I am getting NULL value.
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if(mysqli_query($link, $sqlin)){
$newisid = mysqli_insert_id($link);
$_SESSION['newid'][] = $newisid;
How can I solve this?

php.net : $mysqli->insert_id
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);

Try using mysql_insert_id() to get previously inserted id.
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);//previously insert id here.
} else {
//error
}
See this and this
EDIT
You can also use LAST_INSERT_ID() for this. Check official mysql doc

Try this:
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if($link->query($sqlin)){
$newisid = $link->insert_id;
$_SESSION['newid'][] = $newisid;
}
Reference: http://php.net/manual/en/mysqli.insert-id.php

Related

Passing auto increment id to second query

Currently I've got two queries, where the first one has an auto increment id. I would like to pass this id to my second query. But can't figure out how to do this. I've used 'mysqli_insert_id', but it returned in to the database.
This is my code:
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
$last_id = mysqli_insert_id($con);
second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
To avoid confusion: I want to insert to id of the first query into another table where it will just be an integer.
Hope someone can help me out!
Change your code like that
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($con, $query);
$last_id = mysqli_insert_id($con);
$second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
mysqli_query($con, $second_query);
It will work in this way
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));
$last_id = mysqli_insert_id($link);
second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
mysqli_query($link, $second_query);
/* close connection */
mysqli_close($link);
?>
Refer this
Assuming You are executing your queries,
1. You can use Mysql's function: LAST_INSERT_ID()
Example:
SELECT LAST_INSERT_ID();
2. You can use PHP's function mysqli_insert_id
Example:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
//.. some code
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));

php mysqli_multi_query() stops inserting after first query

I'm trying to insert multiple rows into the same table using a mysqli_multi_query function, but it only executes the first query. I have tried adding the values to the end of the first query separated by a comma as well, but nothing seems to work. Any suggestions?
I've switched to prepared statements but still only the first result is inserted. Am I missing something?
$DBConnect = mysqli_connect("localhost", "root", "", "getpressed");
if ($DBConnect->connect_error) {
die("Connection failed: " . $DBConnect->connect_error);
}
$stmt = $DBConnect->prepare("INSERT INTO orderdetails (orderID, productID, quantity) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $orderID, $productID, $quantity);
$orderID = $orderID;
$productID = 1;
$quantity = $sportShirtQuantity;
$stmt->execute();
$orderID = $orderID;
$productID = 2;
$quantity = $sportCoatQuantity;
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$DBConnect->close();
I had a primary key index on orderID that wouldn't allow me to insert multiple rows with the same orderID. I'm an idiot. Thank you all for your help. It does work much better with prepared statements as suggested by tadman.
I changed your code a bit
$mysqli = new mysqli("localhost", "root", "", "getpressed");
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."');";
if ($mysqli->multi_query($sql))) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
I also highly recommend you to use PDO prepared statements in future.
Remove the semicolon off of the last statement. The documentation notes that the semicolon for this method is used to concatenate statements, not end them.
Read the documentation here: Link
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."')";

Get ID from last insert into table

Im inserting into multiple tables , and need to get the ID from the last insert into table1 and use that as a variable in the insert for table 2.
The IDs is auto incremented.
The query's will be run once a submit button has been clicked in a form.
Query's:
$sql = "INSERT INTO table1 (Text) VALUES ($T1text);";
$sql = "INSERT INTO table2 (table1ID,Text) VALUES ($table1id, $T2text);";
table1 {id,Text}
table2 {id,table1.id,Text}
There is a PHP function for that (Decprecated, Removed in 7.0 !)
Or the according mysql/mysqli/pdo functions.
Solutions
PHP (Deprecated)
Example
$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());
Source: http://php.net/manual/en/function.mysql-insert-id.php
Mysql/Mysqli/PDO
Mysqli
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
PDO
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
Source: http://www.w3schools.com/php/php_mysql_insert_lastid.asp

mysqli last insert id

I would like to associate the image with firstname, lastname...how can I retrieve the last rowand use it to insert to the other table? I tried $image = $mysqli->insert_id; then binding but it doesn't work. Can someone help me out?
$image = $mysqli->insert_id;//this should come from table2
$stmt = $mysqli->prepare("
insert into table1 (username, firstname, lastname, image)
select ?,?,?,image from table2 t2 where username = ? and t2.id = ?
");
$stmt->bind_param('sssss', $username, $fname, $lname, $username, $image);
$stmt->execute();
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query, Example:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
output
New Record has id 1.
Reference
PHP mysqli_insert_id: http://www.php.net/manual/en/mysqli.insert-id.php
First of All you need to create auto_increment field in you ID
Then You can used
$last_id = mysqli_insert_id($conn);
after I get the last row from table2 I would like to insert it to table1. That is all I need
Go on:
insert into table 1 with simple regular insert query
get last insert id
insert into table 2 with simple regular insert query
As simple as that

PHP process page does not work

Hi guys my process page does not work, my code is
<?php
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
$con = mysqli_connect ("localhost", "name", "password", "db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Temp (id, qty, name)
VALUES
('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
header('Location: http://url.com/');
mysqli_close($con);
?>
Should be all correct, just copy from w3school,
The problem is, the db only get 0,
ie. my $id is 4, $qty is 12, $name is "Hello", after the process page, the table only get two 0s in id and qty, name is void.
The values should be processed to this process page successfully, bc I have tried
echo $id, $qty, $name;
All are the same as I typed in before.
Could anyone help me? thanks :-)
this line:
INSERT INTO Temp (id, qty, name) VALUES ('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
should be:
INSERT INTO Temp (id, qty, name) VALUES ('$id', '$qty', '$name')";
If the form is from your previous question, you dont need:
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
I agree it looks like you left out item_. You might want to sanitize your data first.
$id=mysqli_real_escape_string($_POST['item_id']);
$qty=mysqli_real_escape_string($_POST['item_qty']);
$name=mysqli_real_escape_string($_POST['item_name']);
$sql = "INSERT INTO Temp (id, qty, name)
VALUES ('$id', '$qty', '$name')";

Categories