使用foreach php将数据插入到sql表中

时间:2017-12-13 17:15:58

标签: php mysql sql-server

我有一个表单,可以将多个席位发送到php文件。我创建了一个foreach循环来将每个座位插入到sql中。出于某种原因,我能够获得我需要发送的所有信息,但它不会插入。

我不知道它是否与外键有关?但我想要做的是显示哪个电子邮件选择了什么座位。我还希望在将每个座位发送到sql时禁用它。

sql side

这是我的输出。

    You are currently in database admin.


admin@airways.com
1A
1B
1C
Data added successfully.
Back to seating.

这是我的flightselect.php

            <?php
    error_reporting(E_ALL);
    ini_set('display_errors',1);
    include_once 'includes/db_connect.php';
    include_once 'includes/functions.php';
    sec_session_start();

if (login_check($mysqli) == true) {
    $logged = 'in';
} else {
    $logged = 'out';
}
                $username = $_SESSION['username'];
                echo  '<p>You are currently '.$logged. ' database '.$username. '.</p><br>';

                $getemail = mysqli_query($mysqli, "SELECT email FROM members WHERE username = '$username' ");
                $email = '';
                while($gear = mysqli_fetch_array( $getemail )) {
                    echo $gear['email'];
                    $email = $gear['email'];
                } 

                echo $gear."<br>";

    if(isset($_POST['seatme'])){
        if(!empty($_POST['flight'])){
            foreach($_POST['flight'] as $key=>$selected){
                echo $selected."<br>";
                $result = mysqli_query($mysqli, "INSERT INTO seating (seat_id, email, flight_id) 
                                                    VALUES ('$selected', '$gear', '1' )");
            }
        }
    }
        echo "<font color='green'>Data added successfully.";
        echo "<br/><a href='user.php'>Back to seating.</a>";
?> 

1 个答案:

答案 0 :(得分:1)

在VALUES关键字后需要括号...

       if (!mysqli_query($mysqli, "INSERT INTO seating (seat_id, email, flight_id) 
                                   VALUES ('$selected', '$gear', '1' )"))  {
                 printf("Error: %s\n", $mysqli->error);
       }

您还应该了解准备好的语句,因为它们可以使您的SQL更安全。