如何遍历每个数组项并插入数据库

时间:2017-01-25 07:24:03

标签: php mysql arrays

这里有一个包含4个项目的数组。我的PHP脚本遍历每个数组项并应将其插入数据库。现在我无法将所有值插入数据库,它只是添加最后一个数组项的记录。我怎么能这样做?

这就是我所做的:

$project_id = $_GET["pid"];
$today = date('Y-m-d');
$session_array = array("session-1","session-2","session-3","session-4");

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

foreach ($session_array as $sesname) {
    $session_name = $sesname;
    $sql = "INSERT INTO project_sessions (session_date,session_name,project_id) VALUES ('$today','$session_name',$project_id)";
}

if (mysqli_query($conn, $sql)) {
        header("Location: show-project.php?id=$project_id");
} else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

2 个答案:

答案 0 :(得分:0)

将mysql mysqli_query($ conn,$ sql)置于循环内。

$project_id = $_GET["pid"];
$today = date('Y-m-d');
$session_array = array("session-1","session-2","session-3","session-4");

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$error = 0;
foreach ($session_array as $sesname) {
    $session_name = $sesname;
    $sql = "INSERT INTO project_sessions (session_date,session_name,project_id) VALUES ('$today','$session_name',$project_id)";
    if (!mysqli_query($conn, $sql)) {
        $error = 1;
        $error_sql = $sql;
    }
}

if (!$error) {
    header("Location: show-project.php?id=$project_id");
} else {
    echo "Error: " . $error_sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

答案 1 :(得分:0)

尝试这种更有效的方法......

$project_id = $_GET["pid"];
$today = date('Y-m-d');
$session_array = array("session-1","session-2","session-3","session-4");

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO project_sessions (session_date,session_name,project_id) VALUES";

$startLoop = false;
foreach ($session_array as $sesname) {
    $session_name = $sesname;
    $sql .= ($startLoop)?',':'';
    $sql .= "('$today','$session_name',$project_id)";
    $startLoop = true;
}

if($startLoop){
    if (mysqli_query($conn, $sql)) {
            header("Location: show-project.php?id=$project_id");
    } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}
mysqli_close($conn);