从单个表单在数据库中插入多个记录

时间:2014-08-20 17:47:48

标签: php html mysqli

我有以下问题: 当我尝试从表单中将多个记录插入数据库时​​,只插入一个记录。

这是我提交的$ _POST变量的var_dump

array (size=4)
  'date' => string '08-20-2014' (length=10)
  'point_value' => string '987' (length=3)
  'location' => string '46' (length=2)
  'email' => 
    array (size=2)
      0 => string 'thisemail@gmail.com' (length=18)
      1 => string 'test@email.com' (length=14)

和我的用于将数据插入数据库的php脚本(没有显示验证等,但我在脚本中有它)

$email = $_POST['email'];
$points = $mysqli->real_escape_string($_POST['point_value']);
$date = $mysqli->real_escape_string($_POST['date']);
$loc = $mysqli->real_escape_string($_POST['location']);

$count = count($email);
echo $count;
if ($count == '1'){
    $sql1 = "INSERT INTO checkin (checkin_id, date, points, user, location) " . 
            "VALUES (NULL, '".$date."', '".$points."', '".$email."', '".$loc."')";
    $result = $mysqli->query($sql1);
}
else {
    $i = 0; $i < count($email); ++$i;
    $sql1 = "INSERT INTO checkin (checkin_id, date, points, user, location) " . 
            "VALUES (NULL, '".$date."', '".$points."', '". $mysqli->real_escape_string($email[$i])."', '".$loc."')";
    $result = $mysqli->query($sql1);
};

我知道有一种方法可以处理将多个记录插入数据库,但我需要该脚本来处理用户是否只需要插入一条记录或多条记录。

1 个答案:

答案 0 :(得分:0)

这应该有效:

$count = count($email);
for($i = 0; $i < $count; $i++){
    $sql1 = "INSERT INTO checkin (checkin_id, date, points, user, location) 
    VALUES (NULL, '".$date."', '".$points."', '".$email[$i]."', '".$loc."')";
    $result = $mysqli->query($sql1);
};