Insert tables in PHP - php

I have two tables, Order and OrderDetails.
Order Table
OrderID
Order_Details_Id
Date
Cust_Id
Order Details
Order_Details_Id
prod_name
prod_amt
OrderID
Basically i want to insert several order details in one order table. My issue is i am not quite sure how to set OrderID in the Order table to the OrderID in Order Details in PHP. I have made an attempt at it with no luck, this is what i have so far :
$order = "INSERT INTO Order (orderID, cust_id, date)
VALUES ('$cust_id, '23/11/2017')";
$DBcon->exec($order);
foreach ($prodname as $prodname) {
foreach ($prodamount as $prodamount) {
$od = "INSERT INTO Order_Details (OrderDetails_id, prod_name, prod_amt,orderID)
VALUES ('$prodname' , '$prodamount',orderID(?) )";
$DBcon->exec($od);
}
}
Any help would be greatly appreciated, i am relatively new to using PHP and SQL!

Use mysqli::$insert_id to get last inserted id
$DBcon->exec($order);
$orderID = $DBcon->insert_id;
Now use this varibale instead of orderID(?) in your Second INSERTcode.

Related

PHP Deleting multiple rows with returning values to another table

I have a code here that deletes a single row of data from sales_order and then returns the value of the qty to the products table.
<?php
include('connect.php');
//get values from href
$id=$_GET['id'];
$invoice=$_GET['invoice'];
$qty=$_GET['qty'];
$product=$_GET['product'];
//returns quantity to stock
$sql = "UPDATE products
SET stock=stock+?
WHERE productid=?";
$q = $db->prepare($sql);
$q->execute(array($qty,$product));
//execute query
$result = $db->prepare("DELETE FROM sales_order WHERE transaction_id= :id");
$result->bindParam(':id', $id);
$result->execute();
header("location:pos.php?invoice=$invoice");
?>
Now what I'm aiming to do here is to have a reset button that will delete all rows with the same invoice number from sales_order and then each row returns the quantity value to the products table. I can't seem to find a way to do it. Can anyone help me?
You can do an UPDATE with a JOIN:
UPDATE products AS p
JOIN sales_order AS s on s.productid = p.productid
SET p.stock = p.stock + s.quantity
WHERE s.invoice_number = :invoice
Then you can delete all the sales_order rows with that invoice number. You should use a transaction to ensure that this is all done atomically.
I'm making some assumptions above about the schemas of the tables, you'll need to adjust to your actual column names.
I think you can go with an array concept. I think its simple to retrieve all the required values using select query before deletion. Then you can save it to the required tables. The you can delete the values

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

PHP MySQL Insert / Select multiple one to Many

I've been struggling with this one for a while, and have searched various sources (books / the web / this site) but not found a solution yet. I haven't been using PHP / MySQL for that long, so I may not know the relevant vernacular to be able to target my search. Anyway...
I have a basic order management system. The customer can enter multiple lines for an item they want tested, each line having the item to be tested, and the suite of tests required. I then need to expand each of these items into its constituent tests for the test lab to manage its workflow. I need to be able to tie the test back to the order item, and the order.
I have an order table where the overall order is captured with an order_id field (auto-incremented) and some other information (who placed the order etc). I then populate an order item table with the order_id from the order table and each item / test suite combination that the customer wants, each order item has an order_item_id (auto incremented).
$sql1="INSERT INTO tbl_order(od_date, od_customer_id)
SELECT ct_date, ct_customer_id
FROM tbl_cart
WHERE ct_customer_id='$customerID' AND ct_session_id='$sid'";
mysql_query($sql1);
// get order_id
$orderid=mysql_insert_id();
// save order details to tbl_order_item
$sql2="INSERT INTO tbl_order_item(cat_code, pd_code, pd_description, pc_code, smpl_type, test_suite_name)
SELECT cat_code, pd_code, pd_description, pc_code, smpl_type, test_suite_name
FROM tbl_cart
WHERE ct_customer_id='$customerID' AND ct_session_id='$sid'";
mysql_query($sql2);
// update date fields
$sql3="UPDATE tbl_order SET od_date='$date' WHERE ct_date='0000-00-00 00:00:00'";
$sql4="UPDATE tbl_order SET od_username='$username' WHERE od_username=''";
mysql_query($sql3);
mysql_query($sql4);
// set the order id in the order item and lab item tables
$sql5="UPDATE tbl_order_item SET od_id='$orderid' WHERE od_id='0'";
That all works, however I'm now stuck when I try and take each each order item and expand it into its relevant tests. I have created a table which shows the test_suite / test_name combination, but I can't get the output inserted into the lab_item table.
//$sql6="UPDATE tbl_lab_item SET od_id='$orderid' WHERE od_id=''";
mysql_query($sql5);
// Expand Suite into tests in lab item table
$sql7="INSERT INTO tbl_lab_item(od_id,test_name)
VALUES ('$orderid',(SELECT test_name FROM tbl_suite_select WHERE tbl_order_item.test_suite_name=tbl_suite_select.test_suite_name))";
mysql_query($sql7);
Should I be doing this straight into the database, or should I pull the data out into variables first? If so, how?
Many thanks in advance.
UPDATE
I've solved the problem now. Thanks for the input, if anyone is interested, this is was the query that eventually solved it. It was all hinged on calling the right table / cell in the Select for the final table. I was missing a field, so it didn't have a reference.
// Insert individual tests into tbl_lab_item
$sql6="INSERT INTO tbl_lab_item(od_item_id, test_suite_name,test_name)
SELECT tbl_order_item.od_item_id,tbl_order_item.test_suite_name,tbl_suite_select.test_name
FROM tbl_order_item,tbl_suite_select
WHERE tbl_order_item.test_suite_name=tbl_suite_select.test_suite_name";
mysql_query($sql6);
I'm not sure I understand the question fully, but here are some improved queries (using pdo). I think the main point I added was the join statement in the last query. I also combined some of your previous queries to add the rows in one go (instead of inserting than updating). I didn't test anything.
$sqlStmt = $pdo->prepare("
INSERT INTO tbl_order
( od_date
, od_customer_id
, od_date
, od_username)
SELECT
ct_date
, ct_customer_id
, ? AS od_date
, ? AS od_username
FROM tbl_cart
WHERE ct_customer_id = ?
AND ct_session_id = ?
");
$sqlStmt->execute(array(
$date,
$username,
$customerID,
$sid
));
$orderid = $pdo->lastInsertId();
$sqlStmt = $pdo->prepare("
INSERT INTO tbl_order_item
( cat_code
, pd_code
, pd_description
, pc_code
, smpl_type
, test_suite_name
, od_id)
SELECT
cat_code
, pd_code
, pd_description
, pc_code
, smpl_type
, test_suite_name
, ? AS od_id
FROM tbl_cart
WHERE ct_customer_id = ?
AND ct_session_id = ?
");
$sqlStmt->execute(array(
$orderid,
$customerID,
$sid
));
$sqlStmt = $pdo->prepare("
INSERT INTO tbl_lab_item
( od_id
, test_name)
SELECT
? AS od_id
, tss.test_name
FROM tbl_suite_select tss
INNER JOIN tbl_order_item toi
ON toi.test_suite_name = tss.test_suite_name
WHERE toi.od_id = ?
");
$sqlStmt->execute(array(
$orderid,
$orderid
));
This should transform your code into working code:
$sql7="INSERT INTO tbl_lab_item(od_id,test_name)
SELECT '$orderid', test_name FROM tbl_suite_select
WHERE tbl_order_item.test_suite_name=tbl_suite_select.test_suite_name";
I don't quite get whether the condition applied with where is sufficient, though.

Insert image links corresponding to the right product id on MYSQL

I want some help, and I hope you could help me on this.
I'm working in a gallery script, where users create a certain product
and the upload product's images. Now the MySQL part. Here's how I proceed.
-1: Add a new product on the products table: (productid, userid, productname)
$insertproduct="insert into products(userid, productname) values
('3', 'Leather Jacker')";
db->query($insertproduct);
Then I get the productid in this way:
$getproductid = $db->query("SELECT max(productid) from products where userid=3");
while($row = mysqli_fetch_row($getproductid))
{
$pid=$row[0];
}
To later use productid when inserting imagelinks corresponding to that product
$query = "insert into images(imagelink, productid) values
('".$imagelink."', '".$pid."')";
$insert = $db->query($query);
BUT when I check the database everything's fine except for 'productid=0'
so its like:
imgid imagelink productid
166 203572012_1547_17_1.jpg 0
And when I replace $pid with some static number, productid seems to get saved correctly
imgid imagelink productid
166 203572012_1547_17_1.jpg 541
So I'm thinking maybe the problem is here:
while($row = mysqli_fetch_row($getproductid))
{
$pid=$row[0];
}
Help me please. This problem is driving me crazy.
PS: I'm a beginner so please dont judge me :)
Thank you.
replace this $row = mysqli_fetch_row($getproductid) with $row = $getproductid->fetch_row() and i think this too db->query($insertproduct); with $db->query($insertproduct);

Copy multiple rows from one table to another, directly in MySQL?

I am trying to copy values directly from one mysql table to another... but the trouble is, there are many rows to copy, so that sub-select statement will return many rows but the param :order_id is just written once.
Given that problem, I'm having trouble figuring out how to write this process:
# 1: Create new Order & Copy the cart basket to the Order basket
$order_id = addOrder($customer_id);
if ($order_id > -1) {
$sql = "INSERT INTO tbl_order_basket(order_id, product_id, product_name,
basket_qty, basket_price, subtotal)
VALUES (:order_id, (SELECT (cart.product_id, product.name,
cart.cart_qty, cart.cart_price, cart.subtotal)
FROM tbl_shopping_cart AS cart
INNER JOIN tbl_product AS product
ON cart.product_id = product.id
WHERE cart.php_sesskey = :session_id)
)
WHERE order_id=:order_id;";
}
Here is the data I'm trying to copy:
ORDER BASKET CART BASKET PRODUCTS
FK order_id FK php_sesskey
FK product_id <-- FK product_id === PK id
product_name <-- <-- name
basket_qty <-- cart_qty
basket_price <-- cart_price # <-- : copy to
subtotal <-- subtotal # === : join on
How should I go about doing this?
Note: I'm using PHP 5 and MySQL 5.5
Maybe you can use this one?
INSERT INTO ... SELECT ... FROM ... WHERE ...
To create the query, first make a SELECT which gives you all the fields which you want to insert. Then prepend INSERT INTO <table> and you're done.
Look into SELECT INTO TABLE
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
Try using the query below; this type of syntax has worked for me in the past. Since there is no WHERE in a MySQL INSERT statement (manual) I have removed that part. Also, do not use the VALUES keyword when doing an INSERT...SELECT (manual).
$sql = '
INSERT INTO tbl_order_basket(order_id, product_id, product_name,
basket_qty, basket_price, subtotal)
SELECT :order_id, cart.product_id, product.name,
cart.cart_qty, cart.cart_price, cart.subtotal
FROM tbl_shopping_cart AS cart
INNER JOIN tbl_product AS product
ON cart.product_id = product.id
WHERE cart.php_sesskey = :session_id)
';

Categories