user5598179
user5598179

Reputation: 113

How to auto check checkboxes value from database PHP

I'm having a trouble to auto check the checkboxes value I want to auto check the checkbox if its in database for example

$statement = $db->prepare("SELECT * FROM sizestops order by sizestopsID ASC");
$statement->execute();

while($rows = $statement->fetch(PDO::FETCH_ASSOC)) {

  echo "<label style=' display:inline-block;
        width:150px;
        height:50px;
        margin:-1px 4px 0 0;
        vertical-align:middle;'>
        <input type='checkbox' name='sizes[]' class='checkbox' id='sizesprod' onchange='checksize()'  value='" .$rows['sizestopsID']. "'>" . $rows['sizetopsName']  ."</label>";    
 }

Normally it displays SMALL, MEDIUM, LARGE, XLARGE, XXLARGE

But in my database the only saved are

SMALL and MEDIUM only.

In my edit form I want to display that my SMALL and MEDIUM are checked in my checkbox group

How can I do that?

Upvotes: 1

Views: 171

Answers (1)

NullPoiиteя
NullPoiиteя

Reputation: 57312

you can do this by adding checked="checked" in checkbox html when $rows['sizetopsName'] is SMALL or MEDIUM

just do it like

$pre_checked ='';
if($rows['sizetopsName'] == 'SMALL' || $rows['sizetopsName'] =='MEDIUM' ){
  $pre_checked = checked="checked";
}

<input type='checkbox' name='sizes[]' class='checkbox' id='sizesprod' onchange='checksize()'  value='" .$rows['sizestopsID']. "'". $pre_checked.">" 

Upvotes: 1

Related Questions