English 中文(简体)
对照MySQL NUL 价值和PHP
原标题:Checking MySQL NULL values with PHP

这就是我的看法。

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

栏1的违约值为NUL

我想使用col1数据。 如果栏1不作废,则使用栏2数据。

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值。 但是,正如你在第一行可以看到的那样,第二栏并不无效。 我做了什么错误? UPDATE: seeing for a Solutions with PHP and I need both col1 and col2 Value.

我也想学习,是否利用民族解放军的价值观就是这方面的最佳做法?

最佳回答

我看到你的问题:

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

我假定,如果第1栏(IS)不使用第1栏,你就希望使用第2栏数据。 在此情况下,你在你的实验室内有问题。 不知道你是否提供了样本代码,但你没有将任何变数转至该功能,也没有宣布这些变量为千兆克内的全球变量。

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

这使你在这两种情况下都能够这样做。

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

问题回答

您应研究如何使用COALESCE()。 这将使你无法完全需要这一功能/疾病。

SELECT Id, COALESCE(col1, col2)
FROM yourTable

另外,对于PHP,您可考虑修改<条码>。

而是使用<代码>。 它规模较小,更加简明,消除了多少<条码>=待使用标识和打上<条码>的问题。 真实

更新答复,列入安德烈亚斯提出的选择:

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

IFNUL,如果col1不成立,它将给你。 它将给你2栏。

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




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签