Get data from table and Insert into another table from while loop - php

I am having a little issue getting data from a table with while loop. What i want to do is simple I want to take all data from table cart with cookie value from table orders that matches a cookie value and query tables cart to extract data that matches the cookie value in the cart table and place them in table orders_final . Now this is . Now the final part after querying cart table with cookie value gotten from order table, i now want to place the data into orders_final table with all that matches that cookie value from order and cart
$zomo = $_COOKIE['shopa']; // this is the cookie that is stored in the cart table and updated when the transaction is successful
$get_products = "SELECT * FROM `cart` WHERE cookie_value = '$zomo'";
$limo = mysqli_query($con, $get_products);
while($colo = mysqli_fetch_array($limo)){
$product_id = $colo['product_id'];
$order_quantity = $colo['order_quantity'];
$cookie_value = $colo['cookie_value'];
//var $dance is when i update the table with data after payment and data gotten from my payment processing company
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$uii = mysqli_query($con, $dance);
if ($uii){
//this variable insert is where i want to insert all data gotten from cart table above and insert into orders_final, where order table holds the cookie value which was created during shopping which is cookie name shopa held in the variable zomo
$insert = "INSERT INTO `orders_final`(`product_id`, `cookie_value`, `trx_id`, `order_quantities`) VALUES ('$product_id','$zomo','$r_reference','$order_quantity')";
$bena = mysqli_query($con, $insert);
if ($bena){
$delc = "DELETE FROM `cart` WHERE cookie_value = '$zomo'";
$tipee = mysqli_query($con, $delc);
if ($tipee){
perform_success();
}
}
}
}

A better approach is to run fewer queries, that do more. Instead of selecting an entire table and looping over it to run up to 3 queries per iteration (which quickly becomes a lot of queries!), you can use a INSERT INTO...SELECT query instead. Using a transaction, it's also possible to ensure that everything goes through before committing the changes - so you don't end up deleting something that didn't transfer properly.
The code below has been altered to reduce the amount of queries down to three (and none is looped!), and usage of prepared statements has been implemented.
$stmt = $con->prepare("INSERT INTO orders_final (`product_id`, `cookie_value`, `trx_id`, `order_quantities`)
SELECT product_id, ?, order_quantity, ?
FROM cart
WHERE cookie_value=?");
$stmt->bind_param("sss", $zomo, $r_reference, $zomo);
if ($stmt->execute()) {
$stmt->close();
$stmt = $con->prepare("UPDATE orders
SET status=?, time=?, date=?, reference=?, transaction_status=?,
transaction_method=?, final_price=?, order_id=?,
currency=?, referrer=?
WHERE cookie_bought=?");
$stmt->bind_param("sssssssssss", $r_status, $r_time, $r_date, $r_reference, $r_transaction_status, $r_transaction_method, $r_final_price, $r_order_id, $r_currency, $r_referrer, $zomo);
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',
`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$stmt = $con->prepare("DELETE FROM cart WHERE cookie_value=?");
$stmt->bind_param("s", $zomo);
$stmt->execute();
$stmt->close();
}
mysqli::prepare()
mysqli_stmt::bind_param()
MySQL INSERT INTO..SELECT

Related

How can I get the data if I delete it and insert it to another table?

I have a little project which have item management and log history.
Item Management
Item Log
My problem is if I delete the data the last item name that I added is getting inserted in log history instead of the item name that I deleted.
How can I fetch the last item name that I deleted?
Here is my codes on delete button
if(isset($_GET['delete'])) {
$the_item_management_id = $_GET['delete'];
$query = "DELETE FROM item_management WHERE item_management_id = {$the_item_management_id}";
$delete_query = mysqli_query($connection, $query);
$query1 = "INSERT INTO item_management_log (item_code_id, item_name, deleted_stock) VALUES ('$item_code_id', '$item_name', 'deleted $item_name from the stock')";
mysqli_query($connection, $query1);
header("Location:inventory_management.php");
}
I believe you could do this:
if (isset($_GET["delete"])) {
mysqli_begin_transaction($connection); // Using transactions.
// Execute log insertion first.
$stm_log = mysqli_prepare($connection, "INSERT INTO item_management_log (item_code_id, item_name, deleted_stock) VALUES (?, ?, ?)");
$log_message = "deleted $item_name from the stock";
mysqli_stmt_bind_param($stm_log, "iss", $item_code_id, $item_name, $log_message);
mysqli_stmt_execute($stm_log);
// Remove the item later.
$stm_delete = mysqli_prepare($connection, "DELETE FROM item_management WHERE item_management_id = ?");
$the_item_management_id = $_GET["delete"];
mysqli_stmt_bind_param($stm_delete, "i", $the_item_management_id);
mysqli_stmt_execute($stm_delete);
if (mysqli_stmt_affected_rows($stm_delete) > 0) {
mysqli_commit($connection);
} else {
mysqli_rollback($connection); // Undo everything if nothing was deleted.
}
header("Location:inventory_management.php");
}
Why Transactions
You should use transactions because you probably want to log something that actually happened, and so you can abort (through rollback) recording the log if there is an error deleting the item. This way, you won't have an inaccurate log in the database.
Note
I also used mysqli_stmt_affected_rows which makes it possible to know the number of affected records and thus know if an item was really deleted or not.
Also, I believe you should use PDO instead of mysqli, which is a friendlier api. Or at least you should use the mysqli's object-oriented style, which will make your code cleaner and easier to understand.

How to insert data into a certain row?

basically, I used a query to move the data (userid to QTY) from another table (cart) to this table shown below (cart2). After that, i will then insert two sets of data invoice_id and date into the database based on the ord_id.
Below is my database:
From the image, I've tried inserting the data and only the 1st row worked. Subsequent row does not get the subsequent data i inserted.
Here is the code:
$user= $_SESSION['id'];
$trx_id = $_GET['tx'];
$date = date("Y-m-d") ;
Move data from cart to cart2
$move_cart = $db->prepare("INSERT INTO cart2(userid,Product_ID,Product_name,Price,QTY)
SELECT userid,Product_ID,Product_name,Price,QTY FROM cart WHERE userid=?");
$move_cart->bind_param("s",$user);
If it succeeded, delete data from cart
if ($move_cart->execute()) {
$delete_cart =$db->prepare("delete from cart where userid =?");
$delete_cart->bind_param("s", $user);
$delete_cart->execute();
}
> insert data(trx_id and date) to cart 2 based on ord_id
$sql="SELECT * FROM cart2 ";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$ord = $row['ord_id'];
$update_cart = $db->prepare("UPDATE cart2 SET invoice_id =?,date =? WHERE ord_id =?");
$update_cart->bind_param("ssi",$trx_id,$date,$ord);
$update_cart->execute();
$ord ++;
The error is probably in the last piece of code. other codes are just for referencing.

SQL/PHP INSERT INTO multiple rows with $row

So pretty much my issue is that I need to send multiple SQL entries using information based on another SQL entry.
I've simplified the code down that I was using so it's easily understandable.
$sql = mysql_query("SELECT product FROM `cart` WHERE username = '".$user."' LIMIT 10");
while ($rowcart = mysql_fetch_row($sql)) {
$sendorder = "INSERT INTO Orders (order_id, product) VALUES ('NULL', '".$rowcart[0]."')";
mysql_query($sendorder);
}
When I ran it, it had failed to work; so I tried to echo $sendorder to see exactly what was sending and it turns out it's copying the INSERT INTO part on each entry, instead of just copying the values.
Example output:
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Sweets')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Brownies')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
You said, "I need to send multiple SQL entries using information based on another SQL entry." The following approach is more efficient than what you are attempting. Note that I use neither php nor mysql so I might have some syntax errors.
insert into orders
(product)
select product
from cart
where username = $user
As far as the limit 10 goes, if you want to restrict the person to 10 items, you should do something to ensure that only 10 rows go into the cart table.
Mysqli example
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_database');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("SELECT product FROM `cart` WHERE username = ? LIMIT 10");
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($product);
while($stmt->fetch()) {
$tvalue[] = $product;
}
$stmt = $mysqli->prepare("INSERT INTO Orders (product) VALUES (?)");
$stmt->bind_param("s", $one);
foreach ($tvalue as $one) {
$stmt->execute();
}
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
?>
If i understand correctly, what you want to do is to send an unique query, you can do this by appending every value to be inserted at the end of a single query string:
<?php
// code
$sql=mysql_query("SELECT product FROM cart WHERE username='".$user."' LIMIT 10");
$result=mysql_query($sql);
if(mysql_num_rows($result)) {
$rowcart=mysql_fetch_row("$result");
$sendorder="INSERT INTO Orders (order_id, product) VALUES ('NULL', '".$rowcart[0]."')";
while($rowcart=mysql_fetch_row($result))
$sendorder.=", ('NULL', '".$rowcart[0]."')";
mysql_query($sendorder);
}
// code
?>
I assume, your order_id is a primary key, and auto_increment. You can leave that:
INSERT INTO Orders (product) VALUES ('Cakes')
or if you really want to insert it, then use
INSERT INTO Orders (order_id, product) VALUES (NULL, 'Cakes')
if you add quotes ' around it, then it will be parsed as a string. And since, that is not a string, but integer, it will cause syntax error.
You should be able to do this in a single SQL statement something like this..
INSERT INTO Orders(order_id,product)
SELECT null,product
FROM cart
WHERE username = $name
LIMIT 0,10
To refactor even further I would suggest you probably dont need to insert the null value just do:
INSERT INTO Orders(product)
SELECT product
FROM cart
WHERE username = $name
LIMIT 0,10
If your table is structured to allow NULL in the order_id col then this will be populated as null by default.
And as Dan just said doesnt seem to be much point putting a limit on either

PDO bind param in update query

I try to make prepared statament using pdo. It is possible to put several updates atonce?
Ex:
sql1 = "Update product set large = '1large' where id = 1";
sql2 = "Update product set large = '2large' where id = 2";
sql3 = "Update product set large = '3large' where id = 3";
How to prepare sql1,sql2....sqlN in Pdo to execute faster?
I found an example but it works line by line (sql1, sql2 ....)
<?php
$stmt = $dbh->prepare("UPDATE product SET large = ':large' WHERE id = ':id'");
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':large', $large, PDO::PARAM_STR);
$stmt->execute();
?>
Unlike inserts, which can be grouped into a single statement, updates are specific to an existing entry in the database.
Dependant on the broader context of what you are doing you may find a question like this of interest for bulk updates using CASE, WHEN, THEN:
Question: Update multiple rows with one query?

Grab the last insert id from one table to put into another table

probably a simple one for you developers out there
I have this code to insert an order_id and order_name into the 'orders' table:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn = DB();
require_once('header.php');
//should we process the order?
if (isset($_POST['process'])) {
$order_name = $_POST['order_name'];
//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");
//bind the parameters
$stmt->bind_param('s', $order_name);
// Execute query
$stmt->execute();
I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:
//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();
//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {
$prod_id = $item['prod_id'];
$quantity = $item['quantity'];
$prod_type = $item['prod_type'];
$stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");
//bind the parameters
$stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);
// Execute query
$stmt->execute();
}
echo "<p class='black'>Order Processed</p>";
I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.
SQL Server has ##IDENTITY
It looks like mySQL has LAST_INSERT_ID();
My guess is you are using mySQL. If not, then please let me know the version so I can update

Categories