PHP在循环中插入数据库

时间:2015-07-30 23:16:40

标签: php

我试图在for循环中插入多个记录,如下所示:

$connection = mysqli_connect("localhost", "username", "password");
mysqli_select_db($connection, "database");

for ($i = 1; $i <= $_POST['people']; $i++) {

    $stmt = "";

    if ($stmt = $connection->prepare("INSERT INTO `table` (firstname, lastname, email, rsvp) VALUES (?,?,?,?)")) {
        $stmt->bind_param('ssss', "James", "Smith", "smith@abc.com", "yes");
        $stmt->execute();
        $stmt->close();
    }
}

mysql_close($connection);

但它没有插入,我在循环开始时放入一个回声,它只回声一次。请帮忙。

1 个答案:

答案 0 :(得分:1)

首先尝试将所有客户数据分配给变量,如下所示:

$firstname = 'James';
$lastname  = 'Smith';
$email     = 'smith@abc.com';
$rsvp      = 'yes';

$stmt->bind_param('ssss', $firstname, $lastname, $email, $rsvp);