0

我使用 PHP 代码中的 SQL 查询在网站上显示数据库的字段。有没有办法删除空(NULL)字段输出中的空格(whitespaces)?

这是我的代码:

<?php 
    $sql = "SELECT * FROM dining ORDER BY date DESC LIMIT 0, 3";

    $dining = new Database($sql);
    while($dining->results()){

    echo "          
                    <span class='date'>". date("F jS, Y", strtotime($dining->date)) ."</span>
<h3>&nbsp;$dining->title</h3>
<h4>&nbsp;$dining->Comforts</h4> 
&nbsp;$dining->com1<br/>
&nbsp;$dining->com2<br/>
&nbsp;$dining->com3<br/>
&nbsp;$dining->com4<br/>
&nbsp;$dining->com5<br/>
&nbsp;$dining->com6<br/>
<h4>&nbsp;$dining->Breakers</h4>
&nbsp;$dining->break1<br/>
&nbsp;$dining->break2<br/>
<h4>&nbsp;$dining->Wild</h4>
&nbsp;$dining->wild1<br/>
&nbsp;$dining->wild2<br/>
<h4>&nbsp;$dining->Tureens</h4>
&nbsp;$dining->tur1<br/>
&nbsp;$dining->tur2<br/>
&nbsp;$dining->tur3<br/>
<h4>&nbsp;$dining->Desserts</h4>
&nbsp;$dining->des1<br/>
&nbsp;$dining->des2<br/>
&nbsp;$dining->des3<br/>
&nbsp;$dining->des4<br/><br/>
";  
}
?>
4

3 回答 3

1

如果要抑制空白值,则必须单独测试每个值以确定是否应该输出它,例如

if (strlen($dining->des1) > 0) {
   echo "&nbsp;{$dining->des1}<br />";
}
于 2013-09-24T17:12:52.450 回答
0
if(isset(trim($dining->wild1)){
  echo "&nbsp;{$dining->wild1}<br />";
}
于 2013-09-24T17:17:27.697 回答
0

这可能符合要求:

<?php
while($dining->results())
{
    echo "<span class='date'>". date("F jS, Y", strtotime($dining->date)) ."</span>";

if( !empty( $dining->title ) ) echo "<h3>&nbsp;$dining->title</h3>";
if( !empty( $dining->Comforts ) ) echo "<h4>&nbsp;$dining->Comforts</h4> ";
if( !empty( $dining->com1 ) ) echo "&nbsp;$dining->com1<br/>";
if( !empty( $dining->com2 ) ) echo "&nbsp;$dining->com2<br/>";
if( !empty( $dining->com3 ) ) echo "&nbsp;$dining->com3<br/>";
if( !empty( $dining->com4 ) ) echo "&nbsp;$dining->com4<br/>";
if( !empty( $dining->com5 ) ) echo "&nbsp;$dining->com5<br/>";
if( !empty( $dining->com6 ) ) echo "&nbsp;$dining->com6<br/>";
if( !empty( $dining->Breakers ) ) echo "<h4>&nbsp;$dining->Breakers</h4>";
if( !empty( $dining->break1 ) ) echo "&nbsp;$dining->break1<br/>";
if( !empty( $dining->break2 ) ) echo "&nbsp;$dining->break2<br/>";
if( !empty( $dining->Wild ) ) echo "<h4>&nbsp;$dining->Wild</h4>";
if( !empty( $dining->wild1 ) ) echo "&nbsp;$dining->wild1<br/>";
if( !empty( $dining->wild2 ) ) echo "&nbsp;$dining->wild2<br/>";
if( !empty( $dining->Tureens ) ) echo "<h4>&nbsp;$dining->Tureens</h4>";
if( !empty( $dining->tur1 ) ) echo "&nbsp;$dining->tur1<br/>";
if( !empty( $dining->tur2 ) ) echo "&nbsp;$dining->tur2<br/>";
if( !empty( $dining->tur3 ) ) echo "&nbsp;$dining->tur3<br/>";
if( !empty( $dining->Desserts ) ) echo "<h4>&nbsp;$dining->Desserts</h4>";
if( !empty( $dining->des1 ) ) echo "&nbsp;$dining->des1<br/>";
if( !empty( $dining->des2 ) ) echo "&nbsp;$dining->des2<br/>";
if( !empty( $dining->des3 ) ) echo "&nbsp;$dining->des3<br/>";
if( !empty( $dining->des4 ) ) echo "&nbsp;$dining->des4<br/><br/>";

}
?>

empty()当您的值为 NULL 或包含空字符串时,PHP将返回 true。更多在手册中

于 2013-09-24T17:34:36.420 回答