Retrieve id of each INSERT statement in multi query - php

Is it possible to retrieve id (ua_id is in my case) for each INSERT statement in following SQL request
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1);
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2);
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3);
using mysqli::multi_query() to execute it wheres ua_id is AUTO_INCREMENT primary key?

In MySQL you can use LAST_INSERT_ID() function. You need to use this function each time - after INSERT statement. It gets ID for the last inserted record.
MySQL documentation - LAST_INSERT_ID()

Well. you do a multiquery, let's use it:
<?php
$db->multi_query('
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1);
SELECT LAST_INSERT_ID();
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2);
SELECT LAST_INSERT_ID();
INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3);
SELECT LAST_INSERT_ID()') or trigger_error($db->error);
do {
if ($result = $db->store_result()) {
while ($row = $result->fetch_row()) {
var_dump($row);
}
}
} while ($db->next_result());

Do you mean lastInsertId?
http://cl1.php.net/manual/en/mysqli.insert-id.php
hope it helps!

mysqli->insert_id will return the ID of the first row inserted if you insert in the same table you then know that the next row inserted is the first row insert_id + 1...
If you work with many tables at once you then need to scroll back your results then you need to create another query using :
SELECT MAX(id) FROM table-a WHERE 1
...
SELECT MAX(id) FROM table-n WHERE 1
Now I don't know what is better (single insert query or multi query)...

Yes. Use $mysqli->insert_id - see working example below.
$mysqli = new mysqli(host, user, pass, db);
$query = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,1); ";
$query .= "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,2); ";
$query .= "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES (1,3); ";
if ($mysqli->multi_query($query)) {
do {
/* Returns the auto generated id used in the last query */
printf("%d\n", $mysqli->insert_id);
/* Check if loop should continue */
if ($mysqli->more_results() === FALSE) break;
} while ($mysqli->next_result());
}
Use built in mysqli::$insert_id - documentation: http://php.net/manual/en/mysqli.insert-id.php

Related

moving rows to another table and also inserting additional values

Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?
Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";

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

how to do more than query on the same record?

I have this php file to deal with my sql, I want to make many statement on one record in the database
for examole I have this query :
$query = mysql_query("SELECT bloodGroup,quantity,bank_id FROM medical_bank_notification WHERE seen=1");
I want to make all the records which were selected in the $query to have the field seen=0 after it has been selected, so I thought that I have to know all the IDs from the first query and then write another query:
$sql2 = "INSERT INTO medical_bank_notification (seen) VALUES (0) WHERE ID=_????_";
use mysqli_multi_query($con,$query)
$query = "INSERT INTO table1 (column1,column2,column3)
VALUES (value1,value2,value3);";
$query .= "INSERT INTO table2 (column1,column2,column3)
VALUES (value1,value2,value3);";
//excute query
if(mysqli_multi_query($con,$query))
{
while (mysqli_next_result($con) && mysqli_more_results($con))
{
if ($resSet = mysqli_store_result($con)) { mysqli_free_result($resSet); }
if (mysqli_more_results($con)){ }
}
echo 'success';
}

PHP to SqlServer, Getting the last inserted identity

I'm trying to get the last inserted identity in my Orders table in order to insert the same ID into a linked OrderItems table, for each item in my cart array. My Orders table "orderID" is my identity variable, but when I try to pull the most recently inserted value, the result is "null." The original INSERT query into the Orders table is successful, but for some reason the "SELECT ##IDENTITY" query is not.
PHP Code
$ordersquery= "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('{$phonenumber}', '{$time}', 'online')";
echo $ordersquery."\n";
$result= mssql_query($ordersquery, $db);
var_dump($result);
echo mssql_get_last_message();
$idquery= "SELECT ##IDENTITY as id";
$result= mssql_query($idquery, $db);
$id= mssql_fetch_array($result)[$id];
var_dump($id);
foreach ($cart as $item) {
$itemID= $item['id'];
$quantity= $item['quantity'];
$orderitemsquery= "INSERT INTO OrderItems VALUES ('{$id}' '{$itemID}', '{$quantity}')";
if ($resultitems= mssql_query($orderitemsquery, $db)){
echo $orderitemsquery;
}
}
Result
INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('(433) 943-4334', '2015-05-10 14:46:40', 'online')
boolean true
The statement has been terminated.
null
boolean false
Oracle doesn`t have autoincrement. The best you can do, is to get the id first, then do the insert. You get the id like this:
$statement = oci_parse(OCI_CONN, "Select my_seq.nextval from dual");
if (oci_execute($statement)) {
$row = oci_fetch_assoc($statement);
$id = $row['NEXTVAL'];
}
$query = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource); //note this line!!
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
Or - if you prefer "mssql_" extension functions:
$sql = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$results = mssql_fetch_assoc(mssql_query($sql));
$lastid=$results[0];
SCOPE_IDENTITY is generally better because ##IDENTITY is across scopes - it's the last identity inserted into ANY table in the current session, so you better be careful with ##IDENTITY - you can get a value from a trigger or something.

Running a mysql query multiple times using values from an array in the WHERE clause

I need to run a database query multiple times depending in the User ID. Heres my query:
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234')";
I have an array of user ID's from a seperate query shown here:
while($rows=mysql_fetch_array($allresult)){
$birthdays_today[] = $rows['user_id'];
}
echo $birthdays_today[0];
I want the query to run, but there the "userid" = XXXXX in the query, I want that to be populated with a user ID from the array. This means the query must be ran multiple times and each time, the next ID is entered into the query..
Does this make sense?
Thanks :)
MySQL has a bulk insert feature.
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234'), ('XXX2', '23234'), ('XXXX3', '3434545')"
<?php
$query = "INSERT INTO wp_scloyalty (userid, value) VALUES ";
$usersToInsert = array();
foreach($birthdays_today as $user_id){
$usersToInsert[] = "($user_id, '01234')";
}
$query .= implode(',', $usersToInsert);
?>
Use a for loop and change out the query with sprintf() and string formatting.
<?php
foreach($birthdays_today as $uid){
mysql_query(); // ...
}
?>
but
<?php
while($rows=mysql_fetch_array($allresult)){
mysql_query(); // use $rows['user_id'] here
}
?>
I will only display the script after your $birthdays_today[] has been populated.
foreach( $birthdays_today as $thisID )
{
mysql_query( "INSERT INTO wp_scloyalty (userid, value) VALUES ('{$thisID}', '01234');" );
}

Categories