我是PHP编程和MySQL的新手。关于我的问题,我有3个复选框。我需要选择数据并将其保存到数据库中。如果我选择2个数据,那么需要1 × 1保存数据,这意味着将插入两行数据。下面是我的代码示例:
index . php
<!DOCTYPE html>
<html>
<body>
<h1>Show Checkboxes</h1>
<form action="save.php" method="POST">
<input type="checkbox" name="club[]" value="Chelsea">
<label for="Chelsea"> Chelsea</label><br>
<input type="checkbox" name="club[]" value="Liverpool">
<label for="Liverpool"> Liverpool</label><br>
<input type="checkbox" name="club[]" value="Arsenal">
<label for="Arsenal"> Arsenal</label><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
save.php
<?php
include("connect.php");
$club = implode(',',$_POST['club']);
$query = "INSERT INTO bpl_club (club_name) VALUES ('$club')";
$sql = $conn->prepare($query);
$sql->execute();
if($sql){
echo "<script>alert('Record inserted successfully!')</script>";
echo "<script>window.location = 'index.php'</script>";
}else{
echo "<script>alert('Something went wrong. Please try again!')</script>";
}
?>
有人知道怎么修理它吗?非常感谢……
使用foreach函数从$_POST['club']数组中逐一打印复选框
$ClubArray=array();
$ClubArray=$_POST['club'];
foreach($ClubArray as $ClubName)
{
//your Insert code here with the insert query ie INSERT INTO bpl_club (club_name) VALUES ('$ClubName')
}