简体   繁体   中英

Populating checkboxlists from database

Is it possible to populate a checkboxlist from the database values? If so, please suggest how to do this.

$query2 = "select * from Products where CategoryID = '$CategoryName' ";
 mysql_query($query2) or die(mysql_error());
 $array = array();

while($row = mysql_fetch_assoc($query2)){
$array[] = $row;}

foreach($array as $val)
 {
 if($val =='the checkbox value')
  1. Get values from database with the appropriate SQL query
  2. Loop through results echoing out a checkbox element

Caveats

  • Make sure each one has a unique name unless you want them to be an array. Then use array syntax for their name (eg name[])
  • Make sure to give each one a unique value
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>

These are the few steps you have to do. 1.Fetch the values from database. 2. Covert the values in array as they are stored as string by (,) separated. 3. Then

foreach($values as $val)
     {
          if($val =='Bike')
             {
                   $bikeflag = '1';
             }
            if($val =='Car')
             {
                   $carflag = '1';
             }

    }
<form>
<input type="checkbox" name="vehicle" value="Bike"  <?php if(isset($bikeflag ) =='1'){ ?>checked = checked <?php } ?>/> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car"   <?php if(isset($carflag) =='1'){ ?>checked = checked <?php } ?>/> I have a car
</form>

Hopefully this will help you.

Yes, its very much possible:

Fetch the records to be populated with the structure:

Id and value

Provide datasource of the checkedbox list as the fetched structured list as mentioned above.

Now define the value field of the checkboxlist as "Id" and text as "value"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM