我已经熬了两个晚上了,还没能解决这个问题。我是该网站的新手,也是 PHP 的新手,请原谅我的经验不足。这个想法是,当用户选择多个类(class)时,应该将其发送到数据库并存储在单独的行中。现在发生的情况是它只在数据库中存储第一个值两次。谢谢。 代码:
<?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注入(inject)。您应该停止使用 mysql_
函数并切换到 mysqli 或 PDO。
但是现在为了修复错误,您可以更改这部分中的代码:
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();
关于php - 使用 php 将多个复选框中的值插入到 mysql 数据库中的多行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315869/