How to get the value into checkbox

Hi everyone,

I have the value of product size ($prodsize) stored in MySQL table in CSV format, such as “4,5,6”. On the update product page, I have checkbox listed all the possible sizes like this:

<INPUT TYPE=CHECKBOX name=“productsize” value=“3”>Size 3<BR>
<INPUT TYPE=CHECKBOX name=“productsize” value=“4”>Size 4<BR>
<INPUT TYPE=CHECKBOX name=“productsize” value=“5”>Size 5<BR>
<INPUT TYPE=CHECKBOX name=“productsize” value=“6”>Size 6<BR>
<INPUT TYPE=CHECKBOX name=“productsize” value=“7”>Size 7<BR>

If a product’s size is “4,5,6” before the update, what I want on the update page is Size 4, Size 5, Size 6 box is checked. I have no problem retrieve the value of $prodsize from the table, I tried the method below but doesn’t work.


<?php
$sizes = array($prodsize);
?>

<INPUT TYPE=CHECKBOX name="productsize" value="3" <?php if(in_array("3",$sizes)) {echo "checked='yes'";} ?>>Size 3<BR>
<INPUT TYPE=CHECKBOX name="productsize" value="4" <?php if(in_array("4",$sizes)) {echo "checked='yes'";} ?>>Size 4<BR>
<INPUT TYPE=CHECKBOX name="productsize" value="5" <?php if(in_array("5",$sizes)) {echo "checked='yes'";} ?>>Size 5<BR>
<INPUT TYPE=CHECKBOX name="productsize" value="6" <?php if(in_array("6",$sizes)) {echo "checked='yes'";} ?>>Size 6<BR>
<INPUT TYPE=CHECKBOX name="productsize" value="7" <?php if(in_array("7",$sizes)) {echo "checked='yes'";} ?>>Size 7<BR>



How to make it work in PHP?

Many thanks

Are you sure $prodsize is an array? From your description it looks like a string to me.

One way to check your $sizes array is

<?php

$prodsize = "4,5,6";

$sizes = array($prodsize);

foreach($sizes as $key => $value){
    echo 'key: '.$key.' = '.$value.'<br />';
}

die();
?>

thanks webdev for your reply! I’m a beginner of PHP. I guess you are right, it’s a string not an array. But how to solve my problem?

many thanks

ok, let’s assume the sizes for a product are stored in a string like in your op.

Then you can use explode() to break up the string based on a delimeter and output the string parts into an array. Your in_array() should then work.

Modifying the previous demo code:

<?php

$prodsize = "4,5,6";

$sizes = explode(',', $prodsize);  //breakup the string into an array using the comma as a delimeter

foreach($sizes as $key => $value){
    echo 'key: '.$key.' = '.$value.'<br />';
}

?>

the output of the above will now be an array.


key: 0 = 4
key: 1 = 5
key: 2 = 6

Just copy the checkbox code with php, Open Dreamweaver file->new->php and paste it …then execute in the wamp server…

[URL=“http://www.finalyearstudentproject.com/”]

thanks francistomas for your advice! And a big thank to webdev! Following your suggestion, I use emplode to make $sizes to an array, then use implode to make it into a string to update. It works great! Thanks again!!!