I'm trying to add a "checked statement" based upon the users value already entered into the database.

I've designed the database side as q1,q2 etc and have a single varchar with an "a","b", or "c".

I basically want the code to retrieve the answer and put it into the checkbox as "checked", for some reason I just can't get it to work.

Member Avatar

@Boby Smith

php echo checked from database

Post the php & mysql/mysqli code to your problem! Thanks!

OK. Since the code isn't posted to see how things are structured, I can give a hint how you can achieve this.

I'm assuming you've set up your database tables and the script to retrieve the data from the tables. Store the data retrieved from the database in an associate array inside a function so it will be easy to call it in your other files. Then, access the indexed data that was stored in the array.

In your html code, you'd have something like this.


<option> <?php echo $arrayOfData['q1'] ?> </option>
<option> <?php echo $arrayOfData['q2'] ?></option>
<option> <?php echo $arrayOfData['q3'] ?></option>

that all depends on how many q's you've got. if they're more than 5, you're better off using a for-loop. Just a thought.

$chka = ($database_value=='a') ? 'checked' : '';
$chkb = ($database_value=='b') ? 'checked' : '';
$chkc = ($database_value=='c') ? 'checked' : '';

<input type="checkbox" name="chka" <?php echo $chka; ?> value="a" />
<input type="checkbox" name="chkb" <?php echo $chkb; ?> value="b" />
<input type="checkbox" name="chkc" <?php echo $chkc; ?> value="c" />