使用php从多个复选框插入值到mysql数据库的多行


Inserting values from multiple checkboxes into multiple rows in a mysql database using php

我已经熬了两个晚上,我还没能解决这个问题。我是新的网站以及在PHP请原谅我的经验不足。其思想是,当用户选择几个课程时,应该将其发送到数据库并存储在单独的行中。现在发生的情况是,它只在数据库中存储第一个值两次。谢谢。代码:

<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$user_id=$_SESSION['user_id'];
?>
<h2>Register</h2>
<?php
if(isset($_GET['success']) && empty($_GET['success'])){
    echo 'You have successfully registered!';
}
else{
        if(empty($_POST)===false){
        $course[]=$_POST['course_code'];
        $user_id= $user_data['user_id'];
        $username=$user_data['username'];
        foreach($course as $c){
        $data= ''''.implode(''',''',$c).'''';
        mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUE ('$user_id','$username', $data)");
            header('location:courses.php?success');
            exit();
            }
        }
    ?>
    <form action="" method="post">
    <?php
    $sql = "SELECT * FROM course";
    $result = mysql_query($sql)or die(mysql_error());
    echo "<table>";
    echo "<tr><th>COURSE CODE</th><th>COURSE TITLE</th><th>UNIT</th><th>SEMESTER</th><th>LEVEL</th></tr>";
    while($row = mysql_fetch_array($result)){
    $course_code        = $row['course_code'];
    $course_title       = $row['course_title'];
    $course_unit        = $row['course_unit'];
    $semester           = $row['semester'];
    $level              = $row['level'];
    echo "<tr><td style='width: 100px;'>".$course_code."</td><td style='width: 600px;'>".$course_title."</td><td>".$course_unit."</td><td>".$semester."</td><td>".$level."</td><td><input type='"checkbox'" name='"course_code[]'" value=".$course_code."></td></tr>";
    } // End our while loop
    echo "</table>";
    ?>
    <input type="submit" value="Register">
    </form>
<?php
}
include 'includes/overall/footer.php';
?>

你的代码很危险。它不能抵抗sql注入。你应该停止使用mysql_函数,切换到mysqli或PDO。

但是为了修复这个bug,现在你可以在这部分修改你的代码:

foreach($course as $c){
    mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) 
                 VALUES ('$user_id','$username', $c)");
}
header('location:courses.php?success');
exit();

内部循环的重定向停止了进程,所以它只做了一次。为了良好的实践,不要将SQL查询放入循环中,这会使过程变慢。

$values = '';
foreach($course as $c){
    $values .= "('$user_id','$username', '$c'), ";
}
$values = rtrim($values, ',');
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUES {$values}");
header('location:courses.php?success');
exit();

如果你不同意,为什么不写点评论呢?