将两个数组元素逐个插入到DB表中

时间:2012-02-05 03:06:48

标签: php mysql arrays mysqli prepared-statement

我有一些像这样的html表单:

...
<input type="text" id="color"  name="color" value="" placeholder="Color" />
<input type="text" name="size" id="size" value="" placeholder="Size" />
... 

在表单提交期间,我正在检查上面的输入值是否用逗号分隔。

如果是,那就做那样的事情:

  • 假设用户输入,1种颜色:黑色和多种尺寸:42,43,44。代码将插入3倍时间,大小不同但所有其他值都相同

  • 假设用户输入了多种颜色:黑色,黄色和1种尺寸:42。代码将插入2倍时间,颜色不同但所有其他值都相同

问题

如果用户输入了多种颜色和多种尺寸,该怎么办?类似的东西,颜色:黑色,橙色,蓝色和尺寸:45,46,48。代码必须插入9 x时间:黑色 - 45,黑色 - 46 ...蓝色 - 48。我该怎么做?

这是PHP代码:

public function add() {
        if ($_POST['formID'] == 'add_form') {
            $stmt = $this->db->prepare("INSERT INTO `items` 
          (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
          VALUES (?, ?, ?, ?, ?, ?, ?, NOW())") or die($db->error);
            $count = array();
            $size_arr = explode(",", $_POST['size']);
            $color_arr = explode(",", $_POST['color']);
            $count['size'] = count($size_arr);
            $count['color'] = count($color_arr);
            if ($count['color'] > 1) {
                foreach ($color_arr as $color) {
                    $stmt->bind_param("ssiiisi", $_POST['refno'], $color, $_POST['size'], $_POST['qt'], $_POST['stackno'], $_POST['notes'], $_POST['price']) or die($stmt->error);
                    $stmt->execute() or die($stmt->error);
                }
            }
            if ($count['size'] > 1) {
                foreach ($size_arr as $size) {
                    $stmt->bind_param("ssiiisi", $_POST['refno'], $_POST['color'], $size, $_POST['qt'], $_POST['stackno'], $_POST['notes'], $_POST['price']) or die($stmt->error);
                    $stmt->execute() or die($stmt->error);
                }
            } else {
                $stmt->bind_param("ssiiisi", $_POST['refno'], $_POST['color'], $_POST['size'], $_POST['qt'], $_POST['stackno'], $_POST['notes'], $_POST['price']) or die($stmt->error);
                $stmt->execute() or die($stmt->error);
            }
            $stmt->close();
            $this->ajax->respond("nb", "Successfuly added", 1);
        }
    }

1 个答案:

答案 0 :(得分:1)

有两个for循环的强力方法应该有效

foreach ($color_arr as $color) {
     foreach($size_arr as $size) {
          // insert into the database
     }
}