替换MySQL中的NULL值

时间:2013-04-15 12:27:42

标签: php mysql

如何使用它来查找和替换空行.....

$Qemaster="select * from emaster where `branch`='$bid' and `department`='$did' and `status`!='L'";
$Remaster=mysql_query($Qemaster);
while($Rowemaster=mysql_fetch_array($Remaster)){
    $empcode=$Rowemaster[id];
    $name=$Rowemaster[name];
    $Tleave=0;

echo "<tr>";
echo "<td rowspan='2'>".$name."</td>";
echo "<td>Leave</td>";

$Qlp="select * from lpsummary where ((`month` IN(04,05,06,07,08,09,10,11,12) and `year`='$year') or (`month` IN (01,02,03) and `year`='$Nyear')) and `empcode`='$empcode'";
$Rlp=mysql_query($Qlp);
$RRlp=mysql_num_rows($Rlp);
while($Rowlp=mysql_fetch_array($Rlp)){  

$leave=$Rowlp['leave'];
$Tleave=$Tleave+$leave;
if($leave==NULL){
    $Eleave='-';
}
else{
    $Eleave=$leave;
}
echo "<td>".$Eleave."</td>";
}
echo "<td><font color='red'>".$Tleave."</font></td>";
echo "<td><font color='green'>".substr(($Tleave/$RRlp),0,4)."</font></td>";
echo "<tr><td>Percentage</td>";
}

如果有一个空行...我想将其替换为 - 而不是echo“”。$ Eleave。“”;

1 个答案:

答案 0 :(得分:3)

实际上你可以直接通过查询来做到这一点,所以你的php代码中没有任何IF-ELSE条件。使用COALESCE(),例如

另外,养成指定列名的习惯,而不是使用*

SELECT colnames,..., COALESCE(`leave`, '-') `Leave`
FROM   lpsummary
WHERE  .....

更新1

SELECT  COALESCE(l.leave, '-') AS `LEAVE`
FROM    lpsummary l
WHERE   (
            (month IN(04,05,06,07,08,09,10,11,12) and year='$year') or 
            (month IN (01,02,03) and year='$Nyear')
        ) and empcode='$empcode'

作为旁注,如果变量的值( s )来自外部,则查询易受SQL Injection攻击。请查看下面的文章,了解如何防止它。通过使用PreparedStatements,您可以摆脱在值周围使用单引号。