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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址