John Davidson

php - Setting radio buttons from MySQL database


I'm trying to adopt this code taken from but cannot see how I can preset the buttons by PHP based on the value stored in a Boolean MySQL column.

What color do you prefer?<br>
<input type="radio" name="colors" id="yes" value="1" >Yes<br>
<input type="radio" name="colors" id="no" value="0" >No

<button onclick="check()">Check "Yes"</button>
<button onclick="uncheck()">Uncheck "Yes"</button>

function check() {
document.getElementById("yes").checked = true;
function uncheck() {
document.getElementById("yes").checked = false;

My Answer:
You can achieve this by checking the value from the database and setting the "checked" attribute on the radio button that corresponds to the value stored in the database. Here's an example code snippet:

// Assume $row is the row fetched from the database
$option1_checked = $row['column_name'] == 1 ? 'checked' : '';
$option2_checked = $row['column_name'] == 0 ? 'checked' : '';


> Option 1

> Option 2

In this code snippet, we check the value of the column retrieved from the database and set the "checked" attribute on the corresponding radio button. This way, the radio button will be preselected based on the value stored in the database.

Rate this post

3 of 5 based on 1523 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us