0

Example MySQL query: Returned are two values (Desert and Grasslands.) I'd like to match those two values to checkboxes as "checked" Others will stay unchecked.

My PHP result set:

$row[biome];

<?php
while($row = mysqli_fetch_assoc($selectQueryBiomeResult)) {
     echo '<input type="checkbox" name="biomeCheck[]" value="Desert"> Desert';
     echo '<input type="checkbox" name="biomeCheck[]" value="Grasslands"> Grasslands';
     echo '<input type="checkbox" name="biomeCheck[]" value="Deciduous Forest"> Deciduous Forest';
     echo '<input type="checkbox" name="biomeCheck[]" value="Tropical Rainforest"> Tropical Rainforest';
}
?>
1
  • Does the query return only two rows? Commented Dec 30, 2013 at 5:32

2 Answers 2

2

Giving a sample code-

<html>

    <?php
        mysql_connect("host", "username", "pwd") or die("connect error");
        mysql_select_db("db_name");
        $res=mysql_query("write your query here");
        $val_array=array();
        while($row=mysql_fetch_array($res))
        {
            $val_array[]=$row[0];
        }
    ?>

    <body>
        <input type="checkbox" name="biomeCheck[]" value="Desert" <?php if(in_array("Desert", $val_array)) echo "checked"?>> Desert;
        <input type="checkbox" name="biomeCheck[]" value="Grasslands" <?php if(in_array("Grasslands", $val_array)) echo "checked"?>> Grasslands;
        <input type="checkbox" name="biomeCheck[]" value="Deciduous Forest" <?php if(in_array("Deciduous Forest", $val_array)) echo "checked"?>> Deciduous Forest;
        <input type="checkbox" name="biomeCheck[]" value="Tropical Rainforest" <?php if(in_array("Tropical Rainforest", $val_array)) echo "checked"?>> Tropical Rainforest;
    </body>

</html>
Sign up to request clarification or add additional context in comments.

Comments

1

If your result is array then try like this

Example Array

$my_array = array(
    'first' => 'Desert', 
    'second' => 'Grasslands', 
    'third' => 'Deciduous Forest'
);

<input type="checkbox" name="vehicle" value="Desert" <?php if(in_array('Desert', $my_array)) echo( 'checked = "checked"'); ?>/> Desert<br />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.