I have a Boolean column in one of the database table called "status" that i would like to use to control the status of the content being submitted by users, i've set its type to TINYINT and the default value for it is '0' and am using this snippet to apply functionality to the content
$status = '';
if ($row_userDetails['status'] == FALSE) {
$status = 'Not Approved';
}
else {
$status = 'Approved';
}
var_dump($row_userDetails['status']) results are string(0) "0"
And then after i will use the status to display or not to display the content if approved or not respectively.
But my problem is, i can't seem to get a TRUE value i.e "Approved" when i echo $status, i only get the FALSE value i.e "Not Approved". Please help me out on this
You are experiencing a discrepancy due to type-juggling.
It is 99% likely that $row_userDetails['status'] is providing a (string) 'FALSE'
^^ If this is true then use: if($row_userDetails['status'] === 'FALSE') <-- notice the single quotes denoting a string value
The proper way to figure out what type you are working with is to use:
echo gettype($row_userDetails['status']);`
and it will display either boolean, integer, double, string, array, object, resource, or NULL as referenced here
Related
My code looks like this:
$muted = 'true'; //Note this is only for testing
if ($muted == 'false' || $muted == '' || $do_not_text == '' || $do_not_text =='false'){
//do this first thing
}
else{
//do something else
}
I can't get my else to run. What syntax am I messing up?
Related to this, I'm storing a value in my database (that will be what's called to set $muted in my real code) that's either 'true', 'false', or ''. What data type should I be storing these as? Currently, I'm using VARCHAR, but I suspect this is all part of the problem.
$do_not_text == '' evaluates to true. Why? Because $do_not_text is not defined which is a falsy value. You are comparing it to an empty string which also equates to a falsy value. So that comparison is true causing the first if statement to be evaluated as true.
I'm not sure why you're using strings for what should be boolean values.
$muted = true; // no need for quotes
You might also consider using the === operator when comparing boolean values.
if ($muted === false || // etc...
What data type should I be storing these as?
Boolean values in MySQL are typically stored as 1 or 0.
field_name TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
Store them as TINYINT with length of 1 because its only 1 and 0, and 0 as the default value.
Then you can make $muted = boolval($db_muted_val); if you want, or use $db_muted_val as is, because 1 is true and 0 is false.
if ($db_muted_val) {
// do this first thing
} else {
// do something else
}
as the title states ,TINYINT (0, 1) for boolean values in MySQL return true and false value ,,but i want yes and no value when i retrieve TINYINT (0, 1) values from database. is it possible??
Use IF:
SELECT IF(bool_value, 'yes', 'no') as string_value...
tinyint doesnt return true or false. It returns 0 or 1. If you want yes and no, you need to specify that yourself:
if($return == 0) {
return "no";
} else {
return "yes";
}
Yes, it is possible. One way is to add CASE to it:
SELECT
CASE
WHEN value = true THEN 'yes'
ELSE 'no'
END
FROM
`table`;
Another one, as Max suggested, add IF option.
Wanting "yes" and "no" sounds like it's for display purposes, and how you choose to format data from your database/models for display should be in your view oriented code and not the database schema nor the query logic, though there are valid exceptions to the latter. Aside from considerations such as whether "first name" and "last name" as separate items could be useful rather than a single "name" field, decisions about database structure should be based on what you need to store and how different data items relate to each other, not on how data is going to look once retrieved. Particularly as you're using a framework, this should be straightforward.
That said, you could use an enum type instead, defining the enum as enum('no','yes'), though cake may still not have support for enums. You can then get and set string values or numeric ones (1 and 2, or subtract 1 to get 0 and 1). Overall though, tinyint with values 0 and 1 is probably preferable as it's conventional and less likely to lead to mistakes/bugs now or in the future.
Use AppModel::afterFind
http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
public function afterFind($results, $primary = false) {
foreach ($results as $index => $row) {
if (isset($row[$this->alias]['yes_or_no'])) {
$results[$index][$this->alias]['yes_or_no'] = $row[$this->alias]['yes_or_no'] ? 'yes' : 'no';
}
}
return $results;
}
The code below prints out a dropdown box with the default string being --Select Status-- with a value of NULL.
print("<label>Overall Status Overwrite:</label>
<select name='case_ov_status' class='case_ov_status'>
<option selected='selected' value=NULL>--Select Status--</option>");
When the form has been submitted, it will call a function which will determine whether to dropdown box as default value, if not I will update SQL database.
However, this is where I'm confused, the if statement below will still RUN despite submitting a value of NULL.
I found out 2 hours later that by using if($case_ov_status != 'NULL') instead of if($case_ov_status != NULL) solved the problem.
if($case_ov_status != NULL){ //Still ran despite != NULL.
mysql_query("START TRANSACTION", $connection);
$sql = "Update cases set status=".$case_ov_status." Where patientid='".$patientID."' and caseid='".mysql_real_escape_string($case)."'";
$resultNew = mysql_query($sql, $connection);
This may sound really basic, but can someone explain how this works? As I am still learning..
Thanks in advance!
Please read http://php.net/manual/en/language.types.null.php
NULL is a special value to represent unallocated objects in php. "NULL" is a string literal containing the word NULL and is not the same. In PHP however you may see that it will do some type juggling with equality. For example, "" == NULL is true.
You cannot send a PHP NULL value over HTTP since everything is a string in HTTP. So your form even though you specify NULL as a value, will actually send "NULL" to the server.
value=NULL is equivalent to value="NULL". You can't submit non-string values over HTTP. Instead of value=NULL use value="" (empty string). This is falsy for php just like NULL is.
All inputs are ALWAYS represented as string data.
You just have to fill your values with correct values, it cannot be of type null, neither int or smth else.
Possible workaround for you:
Cast every input to integer, if you expect an integer. Like $id = (int) $_GET['id'] ;
Use such functions as empty(). It will return true on "0", 0, null and some other.
you have gotten confused here.
NULL != 'NULL'
The null on the left is a reserved value for a variable that has no value,
The nul on the right is a string containing the word null.
Now to get to your example provided, if you changed your if statement to != 'NULL' (with quotes) you will get your expected result.
if($case_ov_status != "NULL")
My advice however would be to set that value in the option tag to value="" or value="0" and then change your if statement to either :
if($case_ov_status != "")
if($case_ov_status != 0)
or even better
if(!empty($case_ov_status))
when user select <option selected='selected' value=NULL>--Select Status--</option>");, it returns the value you specified in value attribute. it could be 1,2,abc,..or NULL. the string NULL returns as selected value.
when you check if($case_ov_status != NULL), it says $case_ov_status is set to NULL value (that is "") or not? but obviously you need to check if selected value is NULL string. so you have to say if($case_ov_status != 'NULL')
I have a question regarding bools in php. I have a stored mysql proc that is returning a boolean. When this value is grabbed on the php side it displays the value as being a 0 or 1. This all seems fine to me and I have read in the php manual that php will interpret a 0 or 1 as false or true at compile time but this does not seem to be the case to me. I have gone a step further and casted my returned value with (bool) but this still does not seem to work.
My if statements are not properly firing because of this. Does anyone know what is going on? Thanks for the help.
MySQL does not have a proper BOOL or BOOLEAN data types. They are declared as synonyms for TINYINT(1). Your procedure will return 0 or 1, which being on non-PHP ground will get transformed into a string in PHP land, so in PHP you have the strings '0' and '1'.
It is weird however that boolean casting does not convert them to the appropriate booleans. You may have some other bugs in your code.
Are you trying to cast the direct result from the query? Because that one is probably an array and:
var_dump((bool) array('0')); // true
Maybe this is your problem. Inspect the returned result.
It sounds like the boolean value is being returned as a string.
Try something like this:
$your_bool = $field_value === "0" ? false : true;
Using the script below. (You'll have to add HTML line break tags before the word "Boolean" inside the left quote to make the output look like my sample; when I do, Firefox interprets them, making the format look strange).
You'll see that the second line produces a null value which MySQL sees as something different from 0 or 1; for TINYINT it stores the PHP true value correctly but nothing for the PHP false, since a null value has no meaning for TINYINT.
Line four shows type casting with (int) is a way to insure that both PHP true and false are stored to MySQL TINYINT Boolean fields. Retrieving the resultant integers from MySQL into PHP variables works since integers are implicitly cast when assigned to PHP Boolean variables.
echo "Boolean true=".true;
echo "Boolean false=".false;
echo "Boolean (int)true=".(int)true;
echo "Boolean (int)false=".(int)false;
Here's the output from PHP 5.3.1 for MySQL 5.1.41:
Boolean true=1
Boolean false=
Boolean (int)true=1
Boolean (int)false=0
Oh! And PHP Boolean literals may be all lowercase or uppercase with the same result... try it yourself.
I use a helpful function "to_bool" for anything I'm not sure of the type of:
function to_bool($value, $default = false)
{
if (is_bool($value)) {
return $value;
}
if (!is_scalar($value)) {
return $default;
}
$value = strtolower($value);
if (strpos(";1;t;y;yes;on;enabled;true;", ";$value;") !== false) {
return true;
}
if (strpos(";0;f;n;no;off;disabled;false;null;;", ";$value;") !== false) {
return false;
}
return $default;
}
Then:
if (to_bool($row['result'])) { ... }
EDIT: I believe my confusion is probably created by this code at the top of the page in which I'm testing for the value of the option... This creates a shortcut method to refer to the option without using the get_option('option') method...
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) {
$$value['id'] = $value['std'];
} else {
$$value['id'] = get_settings( $value['id'] );
}
}
And so when I set the value of a variable, $myvar, via a checkbox checked in my theme's options panel and click save, then view my options.php in worpdress, the value of the variable is
true
And when I do a lookup on this variable using
if($myvar == "true")
It passes.
However, when I set the value directly via the update_options() method, like so...
$mvar = true;
update_option('myvar', $myvar);
The value changes from true to 1
And when I do the same comparison as before, if($myvar == "true"), it now fails. It is no longer "true".
What am I missing? (1) why is "true" and 1, not evaluating the same and (2) What is the update_option method doing to the value of myvar to change the value from true to 1?
Try
if($myvar == true)
and
$myvar = true;
TRUE and FALSE are PHP's built in boolean variables which are much more universal than a true string.
About the update_option. It might not be that the option is changing it to 1. Instead it might be that the when it is inserting it into the database, it inserts it as the string "true". Then, when it comes back it is converted to the boolean value true, which when printed is 1
Try
if ($myvar)
Don't test whether things "equal" true, they are either true or they aren't.
You should change your first test to if($myvar == true) or simply if ($myvar). PHP has some strange rules for what is "true"; Generally, strings evaulate to true, except the special cases of "0" and an empty string "", which type-cast to false.
In your specific example, if ($myvar == "true"):
If $myvar contains a boolean, the expression will evaluate as (bool) == (bool)"true", or (bool) == true
If $myvar contains an integer, it's cast to a string and compared against the string "true"; so your test is failing, because "1" != "true".
If $myvar is a string, string comparison takes place and suddenly only the literal string "true" will successfully compare.
I would guess 2nd and 3rd cases are in effect: Wordpress is likely setting $myval to the string "true" when the from is posted back, so your test passes. When you manually specify boolean true, Wordpress must be converting it to an integer, and then integer comparison takes place and fails, because the integer 1 will be cast to string "1" when compared against "true".
You are doing a loose comparison between the integer 1 and the string 'true'. For this PHP will translate the string to a number. 'test' as a number is 0:
var_dump((int) 'true'); // int(0)
And since 0 is not equal to 1, the comparison will return false.
Like some other answers already correctly pointed out, you should test against the boolean literal TRUE or true. If one operator in a equality check is a boolean, PHP will convert the other operator to a boolean too, which, for the number 1, will give
var_dump((bool) 1); // boolean(true)
And then your test will pass, because true is equal to true.
Check out the Type Comparison Table to understand how PHP juggles types when testing for equality.
As for what check_update does to your boolean, check out the function description:
(mixed) (required) The NEW value for this option name. This value can be a string, an array, an object or a serialized value.
So, no boolean allowed. I've tried briefly to find out from the sourcecode where the conversion takes place, but since WP is a mess to me, couldn't find it. Like someone else suggested, it probably happens when storing it to the database and then getting it back.
"true" is a string, and all strings evaulates to the boolean 1 (try casting (bool) $string. true on the other hand, without quotes, is a boolean and will evaluate to 1.