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)
';
Related
I have a table named purchase_details_master and another is sales_detais_master Where all the purchase and sales details are available.
Structure of Purchase Table: These are the data which I have purchased
Structure of Sales Table: These are the data which I have sell
Now I need to show the data like this, This image is showing the iPhone 12 data. In the Inward field showing tha pieces of purchased item, In the Outward field showing the data of sells pieces, and the closing data showing like Opening + Inward or Opening - Outward = Closing
I am using Core Php with Sqlite database
$item = $_POST['item'];
$sql = "SELECT * FROM purchase_details_master WHERE item_id = '$item'";
$sql_run = $conn->query($sql);
I have used while loop it's not solving the problem
Kindly solve this out for me! Thank you in Advance
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
like that.
SELECT * FROM purchase_details_master AS pdm INNER JOIN sales_detais_master AS sdm ON sdm.item_id = pdm.item_id WHERE sdm.item_id = ?
this will select all fields from the two tables
$sql = "SELECT * FROM purchase_details_master, sales_detais_master WHERE purchase_details_master.item_id = '$item' AND purchase_details_master.item_id = sales_details_master.item_id";
or select exact fields from the two tables
SELECT table1.field1, table1.field2, table2.field1, table2.field3
FROM table1, table2,
WHERE table1.field1 = something, or table1.field1 = table2.field2
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
I have 5 different tables in my dB with the structure Name|Price|Id..
I have a unique price and Id entry combination.
Using these 2, what could be the possible SQL query to fetch the name of the table in which this entry is present?
I need to fetch the name of this table in order to update the value of Price.
You really should normalise your database properly and use a single table, but if you really need a kludge then:
SELECT name, brand, id, 'Tea' as tablename
FROM TableTea
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Coffee' as tablename
FROM TableCoffee
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Chocolate' as tablename
FROM TableChocolate
WHERE brand = 'abc'
AND id = 100
And you'll have to change it if you ever add new products
if your DBMS is MySQL you can use this Query:
SELECT Result.TABLE_NAME FROM (
SELECT TABLE_NAME,COLUMN_NAME,COUNT(*) AS QTA FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'NAME_DB'
and COLUMN_NAME IN ('Name','Price','Id')
GROUP BY TABLE_NAME
) as Result
WHERE Result.QTA = 3
i have already tried to do without php
Replace NAME_DB with your Database.
You would first need to know the tables in which it's possible to have the entry. Use a loop to iterate over those tables and run the query, each time returning a result set and testing if records exist in the result set. This will tell you what tables have the entry.
General Approach:
$array = array("table1", "table2", "table3", "table4", "table5");
foreach($array as $table) {
//build your query using the table name
$query = "SELECT something FROM " . $table;
//exec your query against your db and return results
//test if records exist in result set. If true, you know the table name based on the loop iteration ($table).
}
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
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.