I have a problem on passing the input value of checkbox array to POST but it doesn't work at all. The following codes are about how I pass the input value of checkbox array to POST. The database and the server work fine as I tried only the value instead of passing variables and it works in this case and it must be the problem of the coding part. I tried several approaches from others but it didn't work at all. Does anyone have any idea? Thanks!
The checkbox part in input form:
<form action='' method='post'>
<input type='hidden' name='postID' value='<?php echo $row['postID'];?>'>
<p><label>Title</label><br />
<input type='text' name='postTitle' value='<?php echo $row['postTitle'];?>'></p>
<p><label>Description</label><br />
<textarea name='postDesc' cols='60' rows='10'><?php echo $row['postDesc'];?></textarea></p>
<p><label>Content</label><br />
<textarea name='postCont' cols='60' rows='10'><?php echo $row['postCont'];?></textarea></p>
<fieldset>
<legend>Categories</legend>
<?php
$stmt2 = $db->query('SELECT catID, catTitle FROM blog_cats ORDER BY catTitle');
while($row2 = $stmt2->fetch()){
$stmt3 = $db->prepare('SELECT catID FROM blog_cat_cats WHERE catID=:catID AND postID=:postID');
$stmt3->execute(array(':catID'=> $row2['catID'],':postID'=> $row['postID']));
$row3 = $stmt3->fetch();
if($row3['catID'] == $row2['catID']){
$checked = 'checked="checked"';
} else {
$checked = '';
}?>
<input type='checkbox' name='catIDlist[]' value='<?php echo $row2['catID']; ?>' <?php echo $checked;?>> <?php echo $row2['catTitle']; ?><br/>
<?php }
?>
</fieldset>
<p><input type='submit' name='submit' value='Update'></p>
</form>
The POST part to retrieve the value from the checkbox
<?php if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST);
//collect form data
extract($_POST);
//Check the valid input from the form
if($postID ==''){
$error[] = 'This post is missing a valid id.';
}
if($postTitle ==''){
$error[] = 'Please enter the title.';
}
if($postDesc ==''){
$error[] = 'Please enter the description.';
}
if($postCont ==''){
$error[] = 'Please enter the content.';
}
if(!isset($error)){
try {
$stmt = $db->prepare('UPDATE blog_posts SET postTitle = :postTitle, postDesc = :postDesc, postCont = :postCont WHERE postID =:postID');
$stmt->execute(array(
':postTitle' => $postTitle,
':postDesc' => $postDesc,
':postCont' => $postCont,
':postID' => $postID
));
$stmt = $db->prepare('DELETE FROM blog_cat_cats WHERE postID = :postID');
$stmt->execute(array(':postID' => $postID));
$catlist = array();
$stmt = $db->prepare('DELETE FROM blog_cat_cats WHERE postID = :postID');
$stmt->execute(array(':postID' => $postID));
if(is_array($catIDlist)){
foreach($_POST['catIDlist'] as $catvalue){
$stmt = $db->prepare('INSERT INTO blog_cat_cats (postID, catID) VALUES (:postID, :catID)');
$stmt->execute(array(
':postID' => $postID,
':catID' => $catvalue
));
}
}
} catch (PDOException $e){
echo $e->getMessage();
}
}
}
} ?>