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;
}
Related
I'm looking at a way of structuring if clauses using the DRY principles of Don't Repeat Yourself.
This is work involving scripts that are ~15 years old and poorly coded with globals etc., and I'm asked to drag this script/site into the 21st Century - but due to time and cost constraints, I can not facilitate a complete site rewrite from scratch, although I know that would be far better.
I have a value that is formerly a global value and I do not know where it comes from and it may come from different places from different pages.
I have some activity that is checking an input value in $_POST or $_GET data, if the input value is empty (or invalid), then check if the value is in fact sat in a $_SESSION. If the input value is still empty (or invalid) then boot to another page.
My code as it stands:
$userId = $_REQUEST['userid'];
if (empty($userId)) {
$userId = $_SESSION['userid'];
}
if(empty($userId) || !is_numeric($userId))
{
header("Location:contactdetails.php");
die();
}
I repeat the empty() function twice, I could wrap both IF's into one line but then would need an IF to pass the value from the REQUEST or the SESSION into the $userId variable.
Is there a (better) way that I can check the two possible inputs to see where this [formerly global] '['userid']' variable is coming from and applying that value to the page-local userId variable?
You can use the ternary operator. The first expression will be used if it evaluates to true, otherwise the latter one. The $_REQUEST superglobal takes precedence in this case, like the code in the question:
$userId = $_REQUEST['userid'] ?: $_SESSION['userid'];
if (empty($userId) || !is_numeric($userId)) {
header("Location:contactdetails.php");
exit;
}
However as Havenard stated in a comment above, blindly trusting request data could be a security issue.
Also note that the condition will be true if any user IDs are 0, in that case a null check would be better:
$userId = $_REQUEST['userid'] ?: $_SESSION['userid'];
if ($userId === null || !is_numeric($userId)) {
header("Location:contactdetails.php");
exit;
}
Of course this is assuming that you do not store falsy values in the $_SESSION as a non-null value.
If $_SESSION['userid'] is guaranteed to be set, rink.attendant.6's answer seem like a clean approach. Otherwise, you will have to perform the necessary checks for both $_REQUEST and $_SESSION to guarantee that $userId is set properly:
if (isset($_REQUEST['userid']) && is_numeric($_REQUEST['userid']))
$userId = $_REQUEST['userid'];
else if (isset($_SESSION['userid']) && is_numeric($_SESSION['userid']))
$userId = $_SESSION['userid'];
else // no acceptable value for $userId in sight
{
header("Location: contactdetails.php");
exit;
}
You might want to reconsider using is_numeric() also, since it validates as true for numeric representations in any format, not just positive integers as you might expect.
There are two different problems you're solving here. First is the problem of defaulting and second is filtering. Take each in turn.
For defaulting, you can implement a simple "get from array if it exists otherwise default" helper:
function array_get(array $a, $key, $default = null) {
return (array_key_exists($key, $a) ? $a[$key] : $default);
}
You can then use this helper to provide default chaining:
$userId = array_get($_REQUEST, 'userid', $_SESSION['userid']);
For filtering, you know from this chain that you've got either a null or a value from one of the two arrays. Since you're looking for ostensibly a database ID, I like a function like this:
function is_id_like($it) {
$rc = filter_var($it, FILTER_VALIDATE_INT, array ('options' => array (
'default' => false, 'min_range' => 1,
)));
return (false === $rc ? false : true);
}
This ensures that the number you give it looks like an int, is 1 or higher, and will return false if not. So all these pass: 1, "1", and "1.0" but these all fail: 0 and "1.1".
Combining these, and allowing for the session to not have a user ID:
$userId = array_get($_REQUEST, 'userid', array_get($_SESSION, 'userid'));
if (! is_id_like($userId)) {
header('Location: contactdetails.php');
die();
}
The total number of checks has changed to one array_key_exists and one filter_var, but the code is substantially more readable and these methods can be reused throughout your code base.
If the value will only ever be set in either the request or session then concat the possible values and validate once.
You should be using if-else for two-way statements and using a switch for n-way statements.
swicth($myVar){
case 1: doX();break;
case 'a': doY();break;
case 2: doZ();break;
default: doA();
}
I have a php project that uses mysqli to query a database. Some of the columns in this database can be null. I have code that looks something like this:
$query = "...";
$result = $DB->query($query);
$row = $result->fetch_assoc();
$column = $row['mycolumn'];
If mycolumn is null, the value of $column appears to be the string, "NULL" (NOT the null value, but actually the string containing the word "NULL"). So what happens if I have columns which actually have the string "NULL" in them? How can I differentiate?
Thanks!
Josh
EDIT:
Upon closer inspection, it appears that the string is actually a 5-characters string. The first 4 characters are "NULL", but the last character is 0x0d, the carriage return. This makes it a lot easier to detect, although I'm still curious if there's a less hack-y way than just doing string comparison.
Use an if condition to check with ===
if($row['mycolumn'] === null) {
echo 'Real Null';
} elseif($row['mycolumn'] == '') {
echo 'Blank';
}
You are looking wrong way. Instead of trying to detect wrong NULL value you have to find out why it is wrong and correct it.
Neither Mysql nor mysqli would return a literal string 'NULL' for a null value.
So, you need to find your own code which converts NULL value to "NULL\n" string either at writing or reading. Are you using raw mysqli as $DB or it's a sort of abstraction class? If so - I'd say problem is there.
After that you can easily read NULL value with strict comparison === as suggested in other answers (though I am not sure about libmysql installations).
seems the column have the data type as string.
If it is string,
we can check by following
if($row['mycolumn'] == '' || is_null($row['mycolumn']))
{
echo "Coulmn is NULL value";
}
else if($row['mycolumn'] == "NULL")
{
echo "Coulmn is NULL value as string";
}
Currently I'm using Tinyint(1) to indicate Boolean values in my MySQL databases, which I really don't like that. So, how could I store and retrieve Boolean values in my MySQL databases via PHP?
How to use it in WHERE clause and how to assign the value in INSERT, UPDATE queries properly?
When I have it back on PHP, it's TRUE, true, or simply 1, if I'm gonna check that with ===?
Also did you ever had any problem when you migrating from Tinyint(1) to BOOLEAN?
Thanks in advance. :)
Update:
I know that Tinyint(1) is the same as Boolean, however I want to work on Boolean data type instead of Tinyint(1). That's why I'm asking the question.
MySQL doesn't have a boolean data type. Tinyint(1) is pretty close enough. Working with this in PHP is simple.
If (1) echo 'true'; // is the same as if (true)
// Just as
if (0) echo 'false'; // is the same as if (false)
And if you really really want a boolean value, you can do
// $mysql_data is tinyint value from db
$boolean = $mysql_data ? true : false;
// Now you have your boolean as $boolean
With booleans, don't use === FALSE - the value is already a boolean (unless the function requires you to use ===, like strpos()). The value is booleanish - it's technically an integer, but PHP is a dynamic language, so it its not a problem.
Consider preg_match() function - it returns the number of matches (integer).
Would you prefer to write that?
if (preg_match('/\bregexp?\b/', $variable) === 1)
Or that?
if (preg_match('/\bregexp?\b/', $variable))
Obviously, the way without explicit === 1 is better. You ask if it matches, not if it has 0 matches. Also, if you think that === 1 is safer, why not do === 1 === TRUE?
Of course, it's possible to convert values to booleans using (bool) or !!.
Also, in certain languages such as C or Perl, there is no difference between booleans and numbers. It just works.
<select name="can_get" id="can_get" class="form-control">
<option <?php if($can_get== "1"){ echo "selected"; } ?>
value="1">True</option>
<option <?php if($can_get== "0"){ echo "selected"; } ?>
value="0">False</option>
</select>
I just wonder how to check if there is a value in a column in a database table? The column is named star and I want to check if it has a value of 1 if not don't do anything.
while($row01 = $res01->fetch_object()) {
if ($res01->star[$row01] == 1) { ??????????
}
}
I use thise WHILE LOOP to fetch info from a table about some objects. For some objects I have a column named STAR that is 1 och NULL. While I build up the HTML-code into variables I in this loop, I also check if the object has 1 in the STAR column and if yes I create another variable with some HTML-code to use in the list of all the objects in the table.
But when I use if($row01->star == '1') it's not working and I don't know why!? When I use this it's like, yes all objects has 1, but there is only a few that has 1, the rest has NULL value. Sorry, but I have to leave the computer for some houres, but I hope to solve this later today! Thanks!
Close, but you're referring to the column wrong.
if ($row01->star == 1) { /* do things */ }
$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
$questionsubmitted=strtolower($_POST[question]);
$currentcheck =$filter[$counter];
$foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
echo $foundvalue;
if ($foundvalue==0) {
$alerter2="true";
} else { }
}
if (!($alerter2=="true")) {
$sql="INSERT INTO Persons (Name, Email, Question)
VALUES
('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
echo "Please only post appropriate questions";
}
For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.
Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.
stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.
You can use === to also check the type of the variable :
if ($foundvalue === 0) {
$alerter2="true";
}
There's more details about this problem in the linked documentation for stripos.
You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.
You need to change
if ($foundvalue==0)
to
if ($foundvalue===0) // three equals signs
or something equivalent, depending on your logic (I didn't quite understand what's going on).
But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).
Also,
$questionsubmitted=strtolower($_POST[question]);
should probably be:
$questionsubmitted=strtolower($_POST['question']);