Detect if empty, has only spaces, or is null - php

I need to know how I can detect if my SQL Server column is empty, with spaces or null.
At the moment I have tested the following ways:
if($prof != NULL)
{
echo 'Test';
} else {
}
This 3 ways below:
if($prof != NULL)
if(empty($prof))
if(is_null($prof))
Any of them is working, my $prof is one column from SQL table, I'm getting the column correctly.
In SQL server the column appears like this:
It looks like that I have spaces in there, but I can't tell PHP to do something if there are those spaces.
I need someone who can help me with this because I already tried more than this and I can't figure out how to solve this, I need to echo test, only if the field is not empty, but since it looks like it contains spaces it also does the echo to the ones that are "empty" it stills echo it.

You can use trim to remove all spaces on the beginning and end of the value:
echo (empty(trim($prof))) ? 'Test' : '';
You can also normalize your values on the SELECT directly:
SELECT LTRIM(RTRIM(ISNULL(Profession, ''))) FROM table_name
After using LTRIM, RTRIM and ISNULL you only need to check for empty string:
echo ($prof === '') ? 'Test' : '';

The pattern I use most often is:
SQL:
SELECT COALESCE( RTRIM(prof), '') FROM MyTable
PHP:
If ($prof == '') {
echo 'Empty!'
}
Note that in SQL, a trimmed NULL is a NULL, not an empty string.

Related

How can I check if the value returned is null?

The code below works I am able to get the color of the car. Now, when the site was made professionally, some of the fields didn't get filled out. So, some of the fields either have a 0, have the word null, empty, or are empty. The one I am interested in is the color column. Some of the fields are empty.
Function getCarColor($cariD){
the rest of my sql code
$carColor = $ref['color'];
return $carColor;
}
What I am stuck in is on how to check if they are empty and add a random text inside, just so that everything looks uniform.
This is my code
Function getCarColor($cariD){
the rest of my sql code
$carColorchk = $ref['color'];
$carColor == is_null (('unspecified') ?: $carColorchk);
return $carColor;
}
Please help. I will eat some extra tamales in your name on christmas dinner.
Try:
you can use null coalesce operator if you are using php 7:
$carColor = $ref['color'] ?? 'nocolor';
or user below if php >=5.3 only
$carColor = $ref['color'] ?: 'nocolor';
There are many ways to do that. You can try the below one:
<?php
if((!empty($your_value)) && ($your_value ! =0) && ($your_value !='')){
//your Code
}
?>

Create An IF Statement If GROUP_CONCAT doesn't return any results

I have a GROUP_CONCAT:
GROUP_CONCAT(CASE WHEN c.twitter IS NOT NULL AND
c.twitter <> '' THEN CONCAT('!',c.twitter) END SEPARATOR ' ') AS tweetWinners
This works great when the user has a twitter name in the database. I then store this like so:
$tweeters = $row['tweetWinners'];
Which gives me a list like:
#twitteruser1 #twitteruser2 #twitteruser3
However, I want to display two different options:
if ($tweeters == '') {
echo "Something";
} else {
echo "$tweeters";
}
But it always jumps to the else even if there aren't any twitter users.
Any help would be appreciated so that I know
GROUP_CONCAT() returns NULL if there are no non-NULL-Values.
see http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat
NULL is not an empty string. COALESCE might help.
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce

How to validate an empty search string

I'm trying to do a search with multiple keywords. For testing purposes ,the search string looks like this
http://localhost/admin/search.php?search=live+concert
So far, the search works perfectly!!!
If there is no parameters, im able to echo a message
if (isset($_GET['search'])) {
// split keywords
$keywords = preg_split('/[\s]+/', $_GET['search']);
// search
} else {
echo 'Nothing to search';
}
Here's my problem. When I hit the search button without entering keywords, i get an empty string , like this
http://localhost/admin/search.php?search=
I want to echo an error to the user saying that there is no keywords to search for. I've tried using count($keywords), but i always get 1 as a result when no keywords have been entered.
How do i check if the user hit the search button without entering keyword(s) ?
Thanks
You can use trim($_GET['search']) where you remove any additional spaces and check if then $_GET['search'] is not '' this way even if the user only submits space, your error message shows
if (isset($_GET['search']) && trim($_GET['search']) != '') {
You might be able try something like this:
if (empty($_GET['search'])) {
echo 'You did not enter anything';
}
empty checks to see if the var is either 0, empty, or not set at all. Not that this matters but as of PHP 5.5 empty() supports expressions, rather than only variables.
You can use simple validation as below, this will check if "search" is posted and its not NULL or not having a while space and length is greater than 0
if (isset($_GET['search']) && strlen(trim($_GET['search']))>0) {
// do the search
}else{
echo 'Nothing to search';
}
If the user has clicked the search button, $_GET['search'] will be set but empty, which is why your 'isset' condition is failing. Why not a simple:
if (!trim($_GET['search'])){ //trim removes whitespace from beginning and end
The empty function should work -
if ( isset($_GET['search']) && !empty(trim($_GET['search'])) )
You can use if ($_GET['search'] == '') {/*ERROR*/} or if (strlen($_GET['search']) < 1) {/*ERROR*/}.
These could also be added to your already existing if statement.
The problem with using count is that when you place an empty string as the second argument for preg_split(), an array with one empty string value will be returned: array(''). Therefore, the amount of values in the array will be one.

empty function not working correctly

I am reading file. I read all data in $part. it is working fine but issue arise when i use empty function. It should display NULL but it is not showing NULL.
My code is as follows:
echo "\nParts------------".$parts[$r]."\n";
echo "\nParts---Size---------".strlen($parts[$r])."\n";
var_dump($parts[$r]);
// $parts[$r]=trim($parts[$r],' ');
//$parts[$r]=str_replace('""','',($parts[$r]));
if(empty($parts[$r]))
{
$entryarray[$c][$c2]='NULL';
}
else if(strlen($parts[$r])<1) //removing special characters
{
$entryarray[$c][$c2]='NULL';
// array_push($entryarray[$c]);
$valueArray=$valueArray.",".'NULL';
}
when i vardump($part) then it is showing its length is 2 instead of 0.
How to display it NULL. i cant write check as if(strlen($parts<2)) cause there is data in file which has lenght less then 2.
I think you meant to use isset instead.
$foo = array("a", "b");
isset($foo[2]); // false
The empty function check if is null or empty string or 0 or something like that.
If you want to chack if is null, i recommend u to use "is_null()"
To check if a key is on array use
array_key_exists($key,$array);

Detect null column value in PHP mysqli

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";
}

Categories