使用PHP检查MySQL NULL值 [英] Checking MySQL NULL values with PHP

查看:440
本文介绍了使用PHP检查MySQL NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的桌子的样子.

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

col1的默认值为NULL.

col1 has a default value of NULL.

我要使用col1数据如果col1不为null,则使用col2数据.

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

这是我的问题.这两个函数均返回$ col2值.但是,正如您在第一行中看到的那样,col2列不为null.我究竟做错了什么? 更新:正在寻找使用PHP的解决方案,并且我需要col1和col2值.

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.

我也想学习,使用NULL值是否是此示例的最佳做法?

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

推荐答案

我在您的问题中发现了很多问题:

I see a slew of problems in your question:

我要使用col1数据如果col2不为null,如果是,我将使用col2数据.

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

我假设您的意思是如果col1为null则要使用col2数据,否则请使用col1.在这种情况下,您的php中就有问题.不知道是否提供了示例代码,但是没有将任何变量传递给该函数,也没有将它们声明为func内部的全局变量.

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

这两种情况都给你一个"a"

This gives you 'a' in both cases

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

这给你'b'

这篇关于使用PHP检查MySQL NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆