2017-05-25 87 views
-1

我網站的一部分顯示了註冊的所有人的列表,但其中一些名稱沒有名字和姓氏,因爲他們沒有完成註冊。目前我擁有它,因此它會顯示列表中的每一個單詞,並顯示具有名稱而沒有名稱的單詞,因此我有很多空白單詞。我怎樣才能讓它只顯示實際名稱字段中的文字?只顯示包含文本的行

這裏是我的代碼:

<?php 

include "../newsmile/db.php"; 
$select = mysqli_query($con,"SELECT * from register where status = '0'"); 
$count = 1; 

while($select1= mysqli_fetch_array($select)) 
{ 
    $selectname = mysqli_query($con,"SELECT * from shipping_detail where User_id = '".$select1['id']."'"); 
    $selectname1= mysqli_fetch_array($selectname); 
    echo '<tr> 
     <td class="center">'.$count.'</td> 
     <td>'.$selectname1['First_name']." ".$selectname1['Last_name'].'</td> 
     <td> 
      <div class="panel-body buttons-widget"> 
       <button type="button" class="btn btn-info userinfo" id = "'.$select1['id'].'">Info 
       </button> 
      </div> 
     </td> 
    </tr>'; 
    $count++;             
} 

?> 
+2

的第一件事錯在這裏是一個循環的第二查詢,您可以使用連接和循環,得到一個查詢中的所有行 – rtfm

+0

@rtfm但我怎麼會讓如果他們真的有文字只顯示在名字列? – user1239315

+1

如果他們在名字列中沒有任何文字,是否仍然要選擇它們? – rtfm

回答

1

你輸出之前添加保護聲明的行

while($select1= mysqli_fetch_array($select)) 
{ 
    $selectname = mysqli_query(
     $con, 
     "SELECT * from shipping_detail where User_id = '".$select1['id']."'" 
    ); 
    $selectname1= mysqli_fetch_array($selectname); 

    if (empty($selectname1['First_name'])) { 
     continue; 
    } 

    if (empty($selectname1['Last_name'])) { 
     continue; 
    } 

    echo '<!-- table row here -->'; 
    $count++; 
} 

也有N + 1點的問題,您應該可以解決。

+0

真棒,這工作,並且你能詳細解釋n + 1問題嗎? – user1239315

+0

爲什麼選擇你不想使用的數據庫行?更好地排除他們在查詢 – rtfm

+0

好點,修復查詢將是一個更好的解決方案。 – Tony

-2

更新查詢以不選擇那些沒有名字的人。

$select = mysqli_query($con,"SELECT * from register where status = '0' AND First_name !='' "); 
0

不要使用SQL字符串連接,這導致你的安全問題
如果設置姓和名欄爲空的默認值,你可以嘗試像下面

while($select1= mysqli_fetch_array($select)) 
{ 
$stmt = $conn->prepare("SELECT * from shipping_detail where User_id = ? and first_name<>null and last_name<>null"); 
$stmt->bind_param("s", $select1['id']); 
// i - integer 
// d - double 
// s - string 
// b - BLOB 



$stmt->execute(); 

$result = $stmt->get_result(); 
     while ($selectname1= $result ->fetch_array()) 
     { 


    echo '<tr> 
     <td class="center">'.$count.'</td> 
     <td>'.$selectname1['First_name']." ".$selectname1['Last_name'].'</td> 
     <td> 
      <div class="panel-body buttons-widget"> 
       <button type="button" class="btn btn-info userinfo" id = "'.$select1['id'].'">Info 
       </button> 
      </div> 
     </td> 
    </tr>'; 

     } 
    $count++;  
    $stmt->close();            
} 

如果您沒有設置默認值,更改查詢如下

$stmt = $conn->prepare("SELECT * from shipping_detail where User_id = ? and first_name<>'' and last_name<>''"); 

你可以閱讀關於這個here