MohammadVHD
MohammadVHD

Reputation: 17

How to set a radio button checked dynamically via php?

In this code we want to read line 7 of a file with our shell and if the value is "set" we want to change the status of our checkbox to checked.

<input type="radio" name="myName" value="myValue"  <?php
     if( shell_exec("./read_from_db 7")=="set") echo ' checked="checked"'
?>

It seems this code those not work. Even though line 7 of the file is "set" the radio button is not checked. Why is that? What's wrong with the code?

Upvotes: 1

Views: 415

Answers (1)

FirstOne
FirstOne

Reputation: 6225

The result coming from shell_exec is giving you something extra.

Try using trim, so:

if( trim(shell_exec("./read_from_db 7"))=="set") echo ' checked="checked"'

Here is a test:

var_dump(shell_exec('echo set'));
echo '<br>';
var_dump(trim(shell_exec('echo set')));
echo '<br>';
$v1 = shell_exec('echo set') == 'set';
$v2 = trim(shell_exec('echo set')) == 'set';
var_dump($v1);
echo '<br>';
var_dump($v2);

and the output:

string(4) "set "
string(3) "set"
bool(false)
bool(true)

You can see that even with no space in the original code, it added something there. My guess is that it is some sort of line break or anything like that.

Upvotes: 1

Related Questions