Sunday, December 4, 2011

PHP: How to evaluate binary variables from a database?

I am trying to have a checkbox checked or not checked on loading a page based on a binary variable read from a database.





The code I am trying to use is (where $centralair holds the binary value):





%26lt;?php


$checked;


if($centralair)


{


$checked="checked";


}


?%26gt;





Central Air:


%26lt;input type="checkbox" name="CentralAir" size="25" %26lt;?php echo $checked ?%26gt; %26gt;





However, the checkbox is always checked. I looked in the database, and it stores binary values with the following characters:





"True" = o


"False" = \0





Any help with this would be greatly appreciated.|||You guys are all wrong.





First of all, you need to give your input tag a value. That value can just be "1". So it would look like: %26lt;input type="checkbox" name="CentralAir" size="25" value="1" %26lt;?php echo $checked ?%26gt; %26gt;





Only checkboxes that are selected show up in the script post.





You then need to pick up that variable. Which would be like this:





$central_air = $_REQUEST['CentralAir'];





Now $central_air has a value of 1, which will evaluate to true;





Then on to setting the $checked variable, you would do this:





$checked = ($central_air) ? "checked=checked" : "";





Here I used the trinary operator. $checked equals the HTML after the ? if $central_air is true (aka 1).





You need to use "checked=checked" as HTML, not just "checked".





That is THE correct way to do what you are trying to do.





Hope this helps.|||Retrieve the value from the database and save it in a variable and try to use javascript function in body's onload event to call that function and sent that variable as a parameter. For Example: check($var);





Define the javascript function, Like this:





%26lt;script type="text/javascript"%26gt;





function check(var) {





if (var == o) {


document.


getElementById("check1").


checked=true;





} else {


document.


getElementById("check1").


checked=false;


}





%26lt;/script%26gt;





Implement to suit your needs.|||What is the data type of your binary column?





If $centralair comes directly from your DB, why not compare it against the two values you listed?





if ($centralair != "\0") $checked = 'checked';

No comments:

Post a Comment