dcp3450
dcp3450

Reputation: 11187

Why is PHP not allowing comparison?

I'm using PHP to read if an entry in my table on the database is set to "yes" or "no" and auto check the radio button that corresponds:

<?php include 'file.php';
$query = "SELECT * FROM TABLE";
$runquery = odbc_exec($connect,$query);
$status= odbc_result($runquery,"status");
odbc_close($file);
?>
<form>
<div class="formContainer">
    <fieldset>
    <legend>Campus Alert<span class="tooltip">Turn campus alert on and off.</span></legend>
        <?php echo $status; ?>
        Yes <input type="radio" name="alertStatus" id="alertStatus" value="yes" <?php if($status== "yes") echo "checked";?>>
        No <input type="radio" name="alertStatus" id="alertStatus" value="no" <?php if($status== "no") echo "checked";?>>
    </fieldset>
</div>

the <?php echo $status; ?> is for debugging so I can make sure what the database says and the form's reaction is correct. It prints "yes" (no quotes). However, the if statement will not respond. Any idea why it's doing this?

Upvotes: 0

Views: 178

Answers (4)

Nick Knight
Nick Knight

Reputation: 11

It's not very good practise to use "yes/no" for your $status, you're better off using an int or boolean value.

Upvotes: 1

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

If you look at the page source you'll see that the check is actually there. However, you have a duplicate ID and the browser is getting confused. Replace:

Yes <input type="radio" name="alertStatus" id="alertStatus" ....>
No <input type="radio" name="alertStatus" id="alertStatus" .....>

with

Yes <input type="radio" name="alertStatus" id="alertStatus:yes" ....>
No <input type="radio" name="alertStatus" id="alertStatus:no" .....>

and it'll fix.

Upvotes: 0

Powerlord
Powerlord

Reputation: 88796

Have you tried changing your if statements to something like

<?php if(strtolower(trim($status)) == "yes") echo "checked";?>

Upvotes: 3

Chibu
Chibu

Reputation: 1353

Wow, that's really weird... the problem isn't with your PHP. First of all, You should remove the id attributes from those fields. But the real issue is that Firefox doesn't seem to want to check the second field when it has the name alertStatus. if you change the name to something else, it seems to be working. I'm not really sure why this is though.

Here's my test code:

<?php //include 'file.php';
//$query = "SELECT * FROM TABLE";
//$runquery = odbc_exec($connect,$query);
//$status= odbc_result($runquery,"status");
//odbc_close($file);
$status='no';
?>
<form>
<div class="formContainer">
    <fieldset>
    <legend>Campus Alert<span class="tooltip">Turn campus alert on and off.</span></legend>
        <?php echo $status; ?>
        Yes <input type="radio" name="alertStatu" value="yes" <?php if($status== "yes") echo "checked";?>>
        No <input type="radio" name="alertStatu" value="no" <?php if($status== "no") echo "checked";?>>
    </fieldset>
</div>

Upvotes: 0

Related Questions