首页 > 解决方案 > Detect if empty, has only spaces, or is null

问题描述

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:

SQL Server Table

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.

标签: phpsql-server

解决方案


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' : '';

推荐阅读