2013-04-15 61 views
1

如何查找和替换空行使用这个时候.....替换NULL值在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>"; 
} 

,如果有一个空行......我想,以取代作为 - 而不是回声“ ”。$ Eleave。 “”;

+1

通过学习如何使用[MySQL的更新](http://dev.mysql.com/doc/refman/5.0/en/update.html)查询。 – Jon

回答

3

其实你可以做,直接通过查询,所以你不会有你的PHP任何IF-ELSE条件code.by使用COALESCE(),如

此外,使它成为一个习惯,不使用*指定列名。

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

UPDATE 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' 

作为旁注,查询是用SQL Injection脆弱,如果变量的值(小号)从外部来了。请看下面的文章,了解如何防止它。通过使用PreparedStatements你可以摆脱使用单引号围绕值。

+0

非常好的功能,我一直在他们想要更新表的印象>< – Jon

+0

谢谢Mr.JW .. 现在我的代码看起来像 $ Qlp =“select leave,COALESCE('leave', (''IN'(04,05,06,07,08,09,10,11,12)和'year' ='$ year')或('month' IN(01) ,02,03)和'year' ='$ Nyear'))和'empcode' ='$ empcode'“; 但获取错误为 警告:mysql_fetch_array():提供的参数不是 – Pilaventhiran

+0

中的有效MySQL结果资源请参阅我的更新答案。 –