[英]updating multiple rows in one sql query
I have to update an arbitrary number of rows for a list of customers, when reminders are sent out to them. 当提醒发送给客户时,我必须为客户列表更新任意数量的行。 I can achieve this through a foreach loop, but I am sure there must be a way of doing this with on query. 我可以通过一个foreach循环来实现这一点,但是我确信必须有一种通过on query做到这一点的方法。
This is what currently works 这是目前有效的
foreach($customer_id_arr as $c) mysqli_query($con,"UPDATE crm_customers SET customer_reminded=1 WHERE customer_id=$c");
How can I do that in one query? 如何在一个查询中做到这一点?
You can leverage implode()
for this: 您可以为此使用implode()
:
mysqli_query($con,"UPDATE crm_customers SET customer_reminded=1 WHERE customer_id IN (" . implode(",",$customer_id_arr) . ")";
It's worth mentioning that you're likely wide open to SQL injection without using prepared statements . 值得一提的是,您可能不使用预备语句就可以进行SQL注入。
Not the nicest way to escape data, but you can do: 这不是逃避数据的最佳方法,但是您可以执行以下操作:
mysqli_query($con,"UPDATE
crm_customers
SET
customer_reminded=1
WHERE customer_id IN (".implode(',', array_map(function($c){return $con->real_escape_string($c);a},$customer_id_arr)).")");
Let's say you need to update customer ID's 1, 2, 3, 4 and 5: 假设您需要更新客户ID的1、2、3、4和5:
UPDATE crm_customers
SET customer_reminded = 1
WHERE customer_id IN (1, 2, 3, 4, 5)
You could even use subqueries in your IN clause. 您甚至可以在IN子句中使用子查询。 Let's say you wanted to set customer_reminded=1 on all records where customer_reminded==0. 假设您要在customer_reminded == 0的所有记录上设置customer_reminded = 1。 Something like: 就像是:
UPDATE crm_customers SET customer_reminded = 1
WHERE customer_id IN
(SELECT customer_id
FROM crm_customers
WHERE customer_reminded == 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.