0

i am showing checkbox from the database, and storing selected checkbox in comma seperated value(CSV) format in the database. now i m facing minor issue to show selected and unselected checkbox while editing. Below my code

<?php

$query = "SELECT * FROM genres";
$result = mysqli_query($conn,$query); //connection working fine

while($fetch = mysqli_fetch_array($result))
{
$allcheckbox[] = $fetch["GenreName"]; // all checkbox from database
}
$selectedcheckbox_array = explode(",", $selectedcheckbox);  // already selected checkbox from database
foreach ($allcheckbox as $key => $value)
{?>

<input type="checkbox" name="genres" id="genres" value="<?php echo "$value" ;?>"
<?php if (isset($selectedcheckbox_array) && in_array("$value" , $selectedcheckbox_array))
{echo 'checked="checked"' ; }?>
/>
<label for="genres"><?php echo "$value" ; ?></label><br />

<?php } ?>

now the issue is not able to show all the selected checkbox from the database, only 1st checkbox displaying with checked find below image. only crime is showing with checked other 2 more checkbox (Horror, political) not checked. Let me know how to solve this issue.

enter image description here

Vetrivel
  • 1,149
  • 1
  • 7
  • 16
  • What are you trying to achieve with `if (isset($selectedcheckbox_array)`? _Of course_ it is set, you did that yourself a couple of lines above. But where is `$selectedcheckbox` actually supposed to come from? – 04FS Oct 08 '20 at 08:14
  • hi $selectedcheckbox come from database, i have tested with print_r() no issue with $selectedcheckbox – Vetrivel Oct 08 '20 at 09:11
  • Do a `var_dump($selectedcheckbox_array);`, and check what that array actually contains. – 04FS Oct 08 '20 at 09:31
  • var_dump() tested, this is the output array(3) { [0]=> string(5) "Crime" [1]=> string(6) " Drama" [2]=> string(8) " Romance" } no issue with $selectedcheckbox_array – Vetrivel Oct 08 '20 at 14:27
  • Really, no issue? `string(6) " Drama"` – the word `Drama` has 5 characters - ` Drama` with a leading space, is something different! Same with `Romance`. You apparently have your values stored separated by a comma _and_ a space, yet you exploded at a comma only. – 04FS Oct 08 '20 at 14:32
  • yes there is white space, now working fine. Thanks for your valuable comments. – Vetrivel Oct 08 '20 at 23:52

0 Answers0