PHP showing stored checkbox data to an update form
I was wondering if anyone could help, I am creating an update product form which is showing results of data already in the database. I want to display all the checkbox categories and have the ones that have already been selected as checked so the user can easily select and change.
I know I am overcomplicating the code below but I am really no sure how to go about this. The code below currently selects all the categories and displays them as checkboxes but I cant get it to display the ones the user开发者_如何学JAVA has already selected and saved to the db as checked. Also I am using MySQL original version not the improved one which I know I should be but If anyone could help I would really appreciate it Thanks Louise.
<?php
$query = "SELECT * FROM category, catid_productid WHERE catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$result = mysql_query($query);
$query = "SELECT * FROM category, catid_productid WHERE category.cat_id = catid_productid.cat_id AND catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$selected_result = mysql_query($query);
$selected_array = array($selected_result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id;
if (isset($_GET['product_id']) && in_array($selected_array['$selected_result'], $selected_array)) {
echo 'checked="checked"';
}
echo " /></li>'";
}
?>
form field:
<div class="field-row ">
<label for="categories"> Categories:<?php
if (isset($required) && in_array('category', $required)) { ?>
<span class="warning">*</span><?php } ?></label>
<div class="fields">
<ul>
<?php
$query = "SELECT * FROM category ORDER BY title ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id.'" /></li>';
}
?>
</ul>
</div>
</div>
inserting it into the database
if($result) {
$product_id = mysql_insert_id();
foreach ($category as $cat_id)
{
// connect to mysql database
mysql_query("INSERT INTO catid_productid (cat_id, product_id) VALUES ('$cat_id', '$product_id')");
}
I don't know if you store checked-or-not information in your DB but I do spot mis-quotation here ..
Try changing this
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id;
To
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id.'"';
AND this
echo " /></li>'";
to
echo ' /></li>';
精彩评论