[英]If value exists in table 1 insert into table 2 mysql
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. 但这只会在具有该ID的客户存在的情况下插入订单。
I think you should think your problem in another way. 我认为您应该以另一种方式考虑您的问题。
Proceed with steps : 继续进行以下步骤:
1 - I need to know if customer my customer exist? 1-我需要知道客户我的客户是否存在吗?
$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";
2- I try my customer, does he exist? 2-我尝试我的客户,他存在吗?
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. 他们说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.