duanhuanyou6478 2011-11-20 23:01
浏览 182
已采纳

使用PHP检查MySQL NULL值

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?

  • 写回答

3条回答 默认 最新

  • douwen1929 2011-11-20 23:39
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题