I’ve been struggling with this problem for the last few days so if anyone can help point me into the right direction I would be grateful. I want to populate a checkbox element in a form where selected checkbox may already be checked depending if the value is set. Before I begin I have to stress that I was handed this problem and would structure the database tables differently but I have to use the current table structure.
I have a product description (string) which contains a list of cartridges. I want to break that string into an array and then loop through and set any cartridge that is already selected to be “checked”.
The string is ‘Single black compatible Blogs BLG001 inkjet cartridge<br />Single colour compatible Blogs BLG002 inkjet cartridge<br />’. Ideally I would like to narrow this string down to just model numbers (BLG001, BLG002). I have split the string into pieces with this code:
<?php
$cartridge = explode("<br />", $setDesc);
?>
I now want to check to see if a Model number exists in the array piece and if it does then mark the checkbox as “checked”.
<?php
if (in_array($cart_model, $cartridge)) {
echo '<input type="checkbox" name="cartridge[]" value="'. $cart_id .'" checked="checked">' . $cart_name.'<br />';
} else {
echo '<input type="checkbox" name="cartridge[]" value="'. $cart_id .'">' . $cart_name.'<br />';
}
?>
now try as I might it will not check the checkboxes that are already in the product description.
Here’s my checkbox query and checkbox code
```php
<div>
<p><strong>Cartridges:</strong></p>
<?php
$result = mysql_query("SELECT p.products_id, pd.products_name FROM products_description pd LEFT JOIN products p ON p.products_id = pd.products_id WHERE pd.products_name LIKE '% Blogs%' ORDER BY pd.products_name ASC") or die(mysql_error());
$cartridges = array();
while(($row = mysql_fetch_assoc($result))) {
$cartridges[] = $row['products_id'];
}
$cartridgeClause = implode("," ,$cartridges);
$result2 = mysql_query("SELECT p.products_id, p.products_model, pd.products_name FROM products_description pd LEFT JOIN products p ON p.products_id = pd.products_id WHERE p.products_id IN($cartridgeClause) ORDER BY pd.products_name ASC") or die(mysql_error());
while ($row = mysql_fetch_array($result2)) {
$cart_id = (int)$row['products_id'];
$cart_model = mysql_real_escape_string($row['products_model']);
$cart_name = $row['products_name'];
if (in_array($cart_model, $cartridge)) {
echo '<input type="checkbox" name="cartridge[]" value="'. $cart_id .'" checked="checked">' . $cart_name.'<br />';
} else {
echo '<input type="checkbox" name="cartridge[]" value="'. $cart_id .'">' . $cart_name.'<br />';
}
}
?>
</div>