mysqli last insert id - php

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

Related

How to insert multiple inputs into the same row that group by the same data

I have a system that records all the user's purchases.
In my system, I have a table called purchase_item.
The table purchase_item looks like this
id
order_id
product_name
1
10001
iphoneX
2
10001
ipnone 12 Pro
3
10001
ipad
4
10002
Apple pen
5
10002
Airpods
6
10002
Iphone 12 Pro Max
This is my query to insert the data above
$osql = "INSERT INTO `purchase_items`(`order_id`, `product_name`) VALUES ('$order_id',`$product_name` )";
Now i created another table(receipt_table) that i want to insert the above data in group. Anyone knows how can i do it?
what I want is the output of my table to look like this:
id
order_id
1
10001
2
10002
I want to group my data by using "INSERT INTO". Anyone knows how can i do that?
Without knowing what sql dialect you use, but in sql server we could do like this:
INSERT INTO receipt_table(id, order_id)
select id, order_id
from purchase_items
group by id, order_id
<?php
$purchased_item = [
[10001, "iPhoneX"],
[10001, "iPhone 12 Pro"],
[10001, "iPad"],
[10002, "Apple Pen"],
[10002, "Airpods"],
[10002, "iPhone 12 Pro Max"]
];
$servername = "localhost";
$username = "root"; //your user name
$password = ""; // your password here
$dbname = "myDB"; // database name
$conn = new mysqli($servername, $username, $password, $dbname);
$osql = "INSERT INTO `purchase_items`(`order_id`, `product_name`) VALUES (?,? )";
$ostmt = $conn->prepare($osql);
$isql = "INSERT INTO reciept_table(`id`, `order_id`) VALUES (?, ?)";
$istmt = $conn->prepare($isql);
$lastId = null; // to check id is entered or not
foreach ($purchased_item as $value) {
$ostmt->bind_param("is", $value[0], $value[1]);
$ostmt->execute();
if ($lastId != $value[0]){
$istmt->bind_param("i", $value[0]);
$istmt->execute();
}
$lastId = $vlaue[0];
}
?>
you can simple use a sql to insert grouped data.and I guess that receipt_table id is an auto_incremnt id.
insert into
receipt_table(order_id)
select order_id from purchase_items
group by order_id;
The way to retrieve the last inserted id in MySQL is $mysqli->insert_id.
$mysqli = new mysqli($servername, $username, $password, $dbname);
$osql = "INSERT INTO `purchase_items`(`order_id`, `product_name`) VALUES (?, ?)";
$stmt = $mysqli->prepare($osql);
$stmt->bind_param("is", $order_id, $product_name);
$stmt->execute();
$id = $mysqli->insert_id;
$rsql = "INSERT INTO receipt_table (order_id) VALUES (?)";
$stmt = $conn->prepare($rsql);
$stmt->bind_param("i", $id);
$stmt->execute();
https://www.php.net/manual/en/mysqli.insert-id.php
https://www.w3schools.com/php/php_mysql_prepared_statements.asp

PHP: How to combine INSERT with UPDATE

My project is a simple attendance record for my small school. I am submitting entry and exit logs through an online form, and writing them to a database with this query:
$sql = "INSERT INTO table_one (first_name, last_name, location)
VALUES ('$first_name', '$last_name', '$location')";
It works fine - so far so good.
At the same moment I would like to write some of this submitted information to another table in the same database. This query works fine by itself when standing alone:
$sql = "UPDATE another_table SET location='$location' WHERE first_name='$first_name'";
However my problem is how to make them both happen, in sequence. Just listing them successively doesn't work:
$sql = "INSERT INTO table_one (first_name, last_name, location) VALUES
('$first_name', '$last_name', '$location')";
$sql = "UPDATE personnel_table SET location='$location' WHERE
first_name='$first_name'";
What is the most effective (and safest) way to combine both commands so that they execute together?
You need to use transaction so that if one query fail, both should fail. Only if both query success that it will add/update the database.
$db= new PDO('mysql:host=localhost; dbname=test', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$db->beginTransaction();
$sh = $db->prepare("INSERT INTO table_one (first_name, last_name, location) VALUES (?, ?, ?)");
$sh->execute([$first_name, $last_name, $location]);
$sh = $db->prepare("UPDATE personnel_table SET location=? WHERE first_name=?");
$sh->execute([$location, $first_name]);
$db->commit();
} catch ( Exception $e ) {
$db->rollBack();
}
for this problem you must use trigger option in database (forEx mysql).
trigger is like an event. when insert in on table automate update second table. forEx:
mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
FOR EACH ROW SET #sum = #sum + NEW.amount;
Query OK, 0 rows affected (0.01 sec)
this trigger that is a object for account table. update #sum variable and then use for update second table
You can create a trigger like below:
delimiter #
create trigger after_ins_trig after insert on first_table
for each row begin
UPDATE second_table
SET new.location=old.location
WHERE new.first_name=old.first_name end#
delimiter ;
You can check id in where clause.
Why not this:
Table: teraz
Create Table: CREATE TABLE `teraz` (
`col` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
//
<?php
$last_name = 77;
$conn = new mysqli('localhost','root','','shopping');
$sql = "INSERT INTO teraz VALUES ('{$last_name}')";
$sql2 = "SELECT * FROM teraz";
$conn->query($sql);
$result = $conn->query($sql2);
$x = $result->fetch_assoc() ;
echo $x['col'];
?>
?

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

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

How to get the last inserted id in 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

Categories