Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve mysql value from php for radio buttons

As trivial as it can seems, I'm having problems retrieving values for radio buttons from MySql database through PHP. It's my first learning project so I'm trying my best

Question has already been asked but I found no useful answer.

The php code does a simple "Select *" so I retrieve all the fields.

This is the php code

<label>Owner: <?php echo $row['Owner']; ?></label></br>
<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "A") { echo "true"; }?>  value="A">A
<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "B") { echo "true"; }?> value="B">B</br></br>

and I retrieve the values with mysqli_fetch_array().

This is the result:

enter image description here

As you can see the label retrieves the correct value, the radio buttons not.

I've already tried putting == instead of = and putting ' instead of " but I don't know why the checkbox "B" is checked, since Owner value is A.

Also, if there are any best practices which are better than this, you're welcome.

like image 630
Liquid Core Avatar asked Dec 15 '22 10:12

Liquid Core


1 Answers

The HTML attribute checked should not get a value, its mere presence indicates that the radio button is checked. So do this:

<label>Owner: <?php echo $row['Owner']; ?></label></br>
<input type="radio" name="Owner" <?php if($row['Owner']=="A") {echo "checked"}?> value="A">A
<input type="radio" name="Owner" <?php if($row['Owner']=="B") {echo "checked"}?> value="B">B

Or using the more compact short echo tag <?= .. ?> and ternary operator:

<label>Owner: <?=$row['Owner']?></label></br>
<input type="radio" name="Owner" <?=$row['Owner']=="A" ? "checked" : ""?> value="A">A
<input type="radio" name="Owner" <?=$row['Owner']=="B" ? "checked" : ""?> value="B">B

Note that you need double equals signs for comparisons.

like image 56
trincot Avatar answered Dec 25 '22 11:12

trincot