John Davidson

php - Setting radio buttons from MySQL database

0 comments
Message:


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


<form>
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
</form>

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

<script>
function check() {
document.getElementById("yes").checked = true;
}
function uncheck() {
document.getElementById("yes").checked = false;
}
</script>


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:

php
// 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

5 of 5 based on 7673 votes

Comments




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