For my ordering system, when an admin inserts an order i need to check if the customer he inserts for the order exists in my customer table.
Im trying something like this, but with no luck..
$sql = "IF EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')
THEN insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
Error: syntax error in first line. What is wrong here?
And is this the right approach? Is there a better way?
you might want to do it "backwards" - insert if exists:
$sql = "insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
select '$customer', '$product', '$quantity', now(), '$note', '$employee'
from dual
where EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')";
Here's a neat trick you can do:
$sql = "INSERT INTO `order`
(`customer_id`, `product`, `quantity`,
`creation_time`, `order_note`, `order_employee`)
SELECT `customer_id`, '$product', '$quantity', now(), '$note', '$employee'
FROM `customer` WHERE `customer_id`='$customer'";
Note that I'm trusting you have already properly sanitised your variables!
But this will only insert the order if the customer with that ID exists.
I think you should think your problem in another way.
Proceed with steps :
1 - I need to know if customer my customer exist?
$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";
2- I try my customer, does he exist?
If(!empty($result_cust)){
$sql = insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
}
With this way your code will be more easily to understand.
Divide and Rule
They said.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.