In the folowing code I am doing an insert from a form into a mysql table
The form fields are populated from an MySQL database, which work correctly.
The problem is extracting data from the multiple checkboxes and inserting each value as a new row in the same table 'selection' columns userid and videoid.
The userid field is inserted correctly, but the videoid is not posting any data.
<?php
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");//connection string
$user=$_POST['userid'];
$checkbox1=$_POST['videoid'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1.",";
}
$in_ch=mysqli_query($con,"INSERT INTO tbl_selection (userid, videoid) VALUES ('$user', '$chk');");
if($in_ch==1)
{
echo'<script>alert("Inserted Successfully")</script>';
}
else
{
echo'<script>alert("Failed To Insert")</script>';
}
}
?>
</body>
</html>
This is the html form which is populated from a mysql table:
<?php
connect to database
?>
<div class="control-group">
<?php
$query = "SELECT * FROM video";
$result2 = mysql_query($query);
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="videoid" value="<?php echo $line[id]?>"><?php echo $line[title]?>
</label>
</div>
<?php } ?>
1) Change
<input type="checkbox" name="videoid" value="<?php echo $line[id]?>"><?php echo $line['title']?>
To
<input type="checkbox" name="videoid[]" value="<?php echo $line[id]?>"><?php echo $line['title']?>
Means, for multiple checkbox. Use name
as array
type. Like videoid[]
.
2) Use for
or foreach
loop for inserting multiple checkbox value into a table. First, find out the checked checkbox through sizeof
. Then, use accordingly.
Updated Code
<?php
$con=mysqli_connect("$host", "$username","$password","$db_name")or die("cannot connect");
$user=$_POST['userid'];
$videoCheckBox=$_POST['videoid'];
$checkedVideo = sizeof($videoCheckBox);
for($i=0;$i<$checkedVideo;$i++) {
$videoId = $videoCheckBox[$i];
$queryVideo = mysqli_query($con,"INSERT INTO `tbl_selection` (`userid`, `videoid`) VALUES ('$user', '$videoId');");
}
if($checkedVideo == 0) {
echo'<script>alert("Failed To Insert")</script>';
} elseif($queryVideo) {
echo'<script>alert("Inserted Successfully")</script>';
}
?>
</body>
</html>
<div class="control-group">
<?php
$query = "SELECT * FROM video";
$result2 = mysql_query($query);
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="videoid[]" value="<?php echo $line['id']?>"><?php echo $line['title']?>
</label>
</div>
<?php } ?>
For more info, please click Inserting data into mySQL table from mutlidimensional input form
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.