2009-04-20 44 views
3

我从数据库中检索3个字段,默认情况下,只有用户名字段将包含内容。其他信息将从用户应用程序中添加。如果该字段中没有条目,我想将该字段显示为“无信息”。我试图使用empty()和is_null()都无济于事。在两种情况下,$ row ['firstname']和$ row ['lastname']的var_dump都返回NULL。检查数据库中的空值 - 失败

<?php 
    if (isset($_GET["subcat"])) 
    $subcat = $_GET["subcat"]; 
if (isset($_GET["searchstring"])) { 
    $searchstring = $_GET["searchstring"]; 
} 
$con = mysqli_connect("localhost","user","password", "database"); 
if (!$con) { 
    echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); 
    exit; 
} 
$table = 'USERS'; 
$brand = '%' . $searchstring . '%'; 
$rows = getRowsByArticleSearch($brand, $table); 
echo "<table border='0' width='100%'><tr>" . "\n"; 
echo "<td width='15%'>Username</td>" . "\n"; 
echo "<td width='15%'>Firstname</td>" . "\n"; 
echo "<td width='15%'>Surname</td>" . "\n"; 
echo "</tr>\n"; 
foreach ($rows as $row) { 
    if (is_null($row['firstname']) || $row['firstname'] == "") { 
     $row['firstname'] == "No Info"; 
    } 
    if ($row['lastname'] == null || $row['lastname'] == "") { 
     $row['firstname'] == "No Info"; 
    } 
    var_dump($row['firstname']); 
    var_dump($row['lastname']); 
    echo '<tr>' . "\n"; 
    echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\',\''.$subcat.'\')">'.$row['username'].'</a></td>' . "\n"; 
    echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['firstname'].'</a></td>' . "\n"; 
    echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['lastname'].'</a></td>' . "\n"; 
    echo '</tr>' . "\n"; 
} 
echo "</table>\n"; 
function getRowsByArticleSearch($searchString, $table) { 
    $con = mysqli_connect("localhost","user","password", "database"); 
    $recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lower(username) LIKE ? "; 
    if ($getRecords = $con->prepare($recordsQuery)) { 
     $getRecords->bind_param("s", $searchString); 
     $getRecords->execute(); 
     $getRecords->bind_result($username, $firstname, $lastname); 
     $rows = array(); 
     while ($getRecords->fetch()) { 
      $row = array(
          'username' => $username, 
          'firstname' => $firstname, 
          'lastname' => $lastname, 
         ); 
      $rows[] = $row; 
     } 
     return $rows; 
    } else { 
     print_r($con->error); 
    } 
} 

回答

4

打开display_errors并将error_reporting设置为E_ALL(无论是在php.ini中还是在htaccess中)。这应该揭示任何非明显的错误。

试试下面的检查,如果事情是空的:

<?php 
if(!isset($row['...']) || empty($row['...'])) 
{ 
    $row['firstname'] = 'No Info'; 
} 
?> 

此外,请注意,您正在使用“==”到$行的东西设置为“无信息”。这个确实是返回'真正'(或1)。使用一个'='来设置变量。

1

两件事情尝试...

if($row['field'] === NULL) { } 

if(isset($row['field'])) { } 
+0

这两种方法没有什么区别。埃。 – 2009-04-20 13:50:39

3

首先,你的主要问题:

您正在使用比较操作符$行[ '姓名'] == “无信息” ;代替分配运营商$ row ['firstname'] =“No Info”;

其他问题:

  • 为什么你建立连接两次?或者实际上多次?找到让您的功能知道连接的方法!
  • 将连接分解为包含。
  • 如果你可以直接访问返回的数组,那么你为什么要这么做while循环呢?