Checking MySQL NULL values with PHP

心不动则不痛 提交于 2020-01-04 06:34:28

问题


This is how my table looks like..

id col1 col2  
---------------
1  a     x
2  NULL  y
3  NULL  z
4  NULL  t

col1 has a default value of NULL.

I want to use col1 data If col1 is not null, otherwise use col2 data.

function something($col1,$col2)
{
   if(is_null($col1) == true)
      $var = $col2
   else
      $var = $col1

   return $var;
}

function something2($col1,$col2)
{
   if($col1 === NULL)
      $var = $col2
   else
      $var = $col1

   return $var;
}

Here is my problem. Both of these functions returns $col2 values. But as you can see in first row, col2 column is not null. What am I doing wrong? UPDATE: Looking for a solution with PHP and I need both col1 and col2 values.

Also I want to learn, Does using NULL values is the best practice for this example?


回答1:


I see a slew of problems in your question:

I want to use col1 data If col2 is not null, If It's I will use col2 data.

I assume you mean you want to use col2 data if col1 IS null otherwise use col1. In that case you have issues in your php. Not sure if you provided sample code or not but you're not passing any variables to the function nor declaring them as global inside the func.

function something($col1, $col2){

  if(is_null($col1) == true)
        $var = $col2;
  else
        $var = $col1;

  return $var;
}

function something2($col1, $col2){

  if($col1 === NULL)
        $var = $col2;
  else
        $var = $col1;

  return $var;
}

echo something('a','x');
echo something2('a','x');

This gives you 'a' in both cases

echo something(NULL,'b');
echo something2(NULL,'b');

This gives you 'b'




回答2:


You should look at using COALESCE() in your sql query, only bring back the data you want to display. This would prevent you from needing this function/logic at all.

SELECT Id, COALESCE(col1, col2)
FROM yourTable

Also, for the PHP, you could consider changing if(is_null($col1) == true)

and using if(is_null($col1)) instead. It is smaller, more concise, and eliminates issues with how many = signs to use, and casing of True

Updating answer to include option proposed by Andreas:

SELECT Id, col1, col2
   , IFNULL(col1, col2) AS NotNullColumn
FROM yourTable



回答3:


Check out IFNULL, it will give you col1 if that isn't null. Else it will give you col2.

SELECT id, IFNULL(col1, col2) FROM <table>;


来源:https://stackoverflow.com/questions/8205502/checking-mysql-null-values-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!