[英]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.