2012-01-16 169 views
1

我有一個頁面顯示來自mysql_query的各個字段。只有當值可用時,我纔想顯示下列字段/行。如何顯示一行,如果它不爲空而不是空的?

$web = $row['Website']; 


<?php 
if ($web = NULL) 
{?> 
<!-- DO NOTHING --> 
<?php 
} 
else 
{?> 
<tr> 
<td valign='top' colspan='3' align='center'><DIV CLASS='standings_title'><?php echo $web ?></div></td> 
</tr> 
<?php 
} 
?> 

希望有人能告訴我我做錯了什麼。

+0

如果($網站= NULL)將無法正常工作。嘗試'if($ web)'或者至少使用比較運算符if($ web == null)。 – TuK 2012-01-16 03:31:26

回答

3
<?php if($web):?> 
<tr> 
<td valign='top' colspan='3' align='center'><DIV CLASS='standings_title'><?php echo $web ?></div></td> 
</tr> 
<?php endif; ?> 
2

使用isset()

if(isset($web)) 
{ 

} 

或者

if($web) 
{ 

} 
+2

你可能想要刪除第二個中的否定。用於檢測空值的 – AlexanderZ 2012-01-16 03:33:28

0
$web = $row['Website']; 
// Trim whitespace so a single blank space doesn't display as a populated value. 
$web = trim($web); 
if (!empty($web) { 
    // Display it. 
} 
3
if (isset($value) && strlen($value) > 0) { 
    //stuff 
} 

這比使用空($值)更好,或只是一個如果($值),因爲PHP考慮的事情,如「0 「爲空。但是,如果您可以保證該值永遠不會爲「0」,則它們在功能上是等效的,並且!empty($ value)會更快。

從PHP手冊:

The following things are considered to be empty: 

"" (an empty string) 
0 (0 as an integer) 
0.0 (0 as a float) 
"0" (0 as a string) 
NULL 
FALSE 
array() (an empty array) 
var $var; (a variable declared, but without a value in a class) 
0

行的柱後如果沒有(在PDO)空:

$sql = 'SELECT * FROM posts where post_date !="" '; 
    $stmt = $database->prepare($sql); 
    $stmt->execute(); 
    $rowCount = $stmt->rowCount(); 

    if($rowCount < 1) 
    { 
     return null; 
    } 
    else 
    { 
     do somthing ... 
    } 
+0

,使用rowCount或columnCount(在PDO中) – Maher 2013-01-12 12:49:01

相關問題