繁体   English   中英

如何用PHP + MySQL中的值替换空查询

[英]How to replace empty query with value in PHP + MySQL

我需要将MySQL返回的查询替换为零(如果为空),但是我不知道怎么做。

例如,我有一个名为values的表。 设备ID和带有值的一段时间。

id_device | 2015-05-01 | 2015-05-02 | 2015-05-03 | 2015-05-04 | 2015-05-05
---------------------------------------------------------------------------
     1    |    1000    |    990     |    980     |    970     |    960    |
     2    |    1150    |    1140    |    1130    |    1120    |    1100   |
     3    |    1050    |    1040    |    1030    |    1020    |    1010   |
     4    |            |            |            |            |           |
     5    |    1250    |    1240    |    1230    |    1220    |    1210   |

当我使用

$sql = mysql_query("SELECT * FROM values");
while ($row = mysql_fetch_array($sql)) {
    if (mysql_num_rows($row) == 0) { 
         $row[1] = 0; $row[2] = 0; $row[3] = 0; $row[4] = 0; $row[5] = 0;
         }
    echo "<td>$row[1] $row[2] $row[3] $row[4] $row[5]</td>";
    }

第4行仍然为空,而不是被零代替。 为什么? 以及如何用零替换空字段?

您可以在SQL查询中进行处理,请参见以下示例:

SELECT `device_id`, IF(`column_name` = '', 0, `column_name`) as col_name FROM `table_name`

除此之外, mysql_num_rows用于在执行的查询中返回数字或行。

编辑:

您可以使用IFNULL ,以防万一,如果要获取空值而不是空格。

这里的问题是您的条件mysql_num_rows 它检查您的SQL查询返回了多少行。 无论您在代码中的什么位置,它都将返回此数字,直到资源对象( $sql )被覆盖为止。

因此,您的代码将执行以下操作:

#execute the sql statement
$sql = mysql_query("SELECT * FROM values);
#get the rows from the sql result, on by one
#the first $row contains id_device #1 and so on
while ($row = mysql_fetch_array($sql)) {
    #here you look up the number of rows your sql statement gets
    #this always returns 5, as the result from your query does not
    #change when looking at the single lines of your result
    if (mysql_num_rows($row) == 0) { 
        #you'll never enter this condintion
        $row[1] = 0; $row[2] = 0; $row[3] = 0; $row[4] = 0; $row[5] = 0;
    }
    echo "<td>$row[1] $row[2] $row[3] $row[4] $row[5]</td>"
}

尝试以下方法:

$sql = mysql_query("SELECT * FROM values);
while ($row = mysql_fetch_array($sql)) {
    #checks if one of the cells is empty
    if (in_array("", $row)){
        #if so, $row will be filled with empty values
        #except for the first element, as this is your device_id
        $row = array_fill(1, count($row), 0);
    }
    echo "<td>$row[1] $row[2] $row[3] $row[4] $row[5]</td>"
}

您正在检查行数是否等于零,但是我知道您想检查是否存在空列,如果该列为NULL或数据库中为空,则MySQL将返回空字符串,因此您只需在内部添加while循环检查每一列是否为空以等于零

例如

if($row[1]=="") $row[1]=0;
if($row[2]=="") $row[2]=0;
if($row[3]=="") $row[3]=0;
if($row[4]=="") $row[4]=0;
if($row[5]=="") $row[5]=0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM