如何处理二维数组,从angular发送到php,用于数据库查询

时间:2015-10-21 15:30:25

标签: php mysql arrays angularjs

我创建了一个具有以下结构的2维数组order_details:

| order_id | product_id |
+==========+============+
|    1     |     2      |
+----------+------------+
|    1     |     3      |
+----------+------------+
|    2     |     4      |
+----------+------------+
|    3     |     2      |
+----------+------------+

我使用post方法将此数组发送到php文件。

在php文件中,我使用以下代码存储数组:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$array = $request;

我想使用这样的数组在mysql中执行更新查询:

UPDATE table_ex SET status='completed' WHERE order_id IN array.order_id AND product_id IN array.product_id

查询之前的Table_ex如下:

| order_id | product_id | status  |
+==========+============+=========+
+----------+------------+---------+
|    5     |     4      | nothing |
+----------+------------+---------+
|    6     |     2      | nothing |
+----------+------------+---------+
|    1     |     2      | nothing |
+----------+------------+---------|
|    1     |     3      | nothing |
+----------+------------+---------+
|    2     |     4      | nothing |
+----------+------------+---------+
|    3     |     2      | nothing |
+----------+------------+---------+

更新后,table_ex应如下所示:

查询之前的Table_ex如下:

| order_id | product_id |   status  |
+==========+============+===========+
|    5     |     4      |  nothing  |
+----------+------------+-----------+
|    6     |     2      |  nothing  |
+----------+------------+-----------+
|    1     |     2      | completed |
+----------+------------+-----------+
|    1     |     3      | completed |
+----------+------------+-----------+
|    2     |     4      | completed |
+----------+------------+-----------+
|    3     |     2      | completed |
+----------+------------+-----------+

你能帮助我吗?

提前致谢,

Giannis

1 个答案:

答案 0 :(得分:1)

您的查询会将order_id = 6,product_id = 2设置为'已完成'同样,因为2位于product_id数组中。使用OR连接的AND子条件解决它,如下所示:

$cond = array();
foreach ($array as $part) {
    $cond[] = sprintf('(order_id="%s" AND product_id="%s")', 
        $part['order_id'], $part['product_id']);
}
$sql = 'UPDATE table_ex SET status='completed' WHERE '.join(' OR ', $cond);

(希望我能正确地得到你阵列的结构。)

这将生成一个看起来像

的查询
UPDATE table_ex SET status='completed' 
  WHERE (order_id="1" AND product_id="2")
  OR (order_id="1" AND product_id="3")
  OR (order_id="2" AND product_id="4")
  OR (order_id="3" AND product_id="2")