2017-07-27 83 views
-1

管理表的foreach警告

+--------------+---------------+ 
| Username  | Password  | 
+--------------+---------------+ 
| JOHN   | 123   | 
| EDWARD  | 123   | 
+--------------+---------------+ 

我的代碼

$result = mysqli_query($connection, $query); 
    echo" <table >"; 
    $row = mysqli_fetch_assoc($result);  
echo "<tr>"; 
    foreach($row as $key => $val){ 
     echo"<th>$key</th> "; 
    echo "</tr>"; 
    /////////////////////////////// 
    $result = mysqli_query($connection, $query); 

     echo"<tr>"; 
    while($row = mysqli_fetch_assoc($result)){ 
    foreach($row as $key => $val){ 
     echo "<td>$val</td>"; 

    } 
    echo "</tr>"; 

    } 


    echo "</table>"; 
} 

那麼,問題是如果在其輸出完全相同的結果超過1行什麼,我想對於例如,如果我說:

SELECT Username from admin; 


     +--------------+ 
     | Username  | 
     +--------------+ 
     | JOHN   | 
     | EDWARD  | 
     +--------------+ 

但如果只有一排它並不顯示列名,並給出此警告

Select Username from admin where Username = 'JOHN'; 

    Warning: Invalid argument supplied for foreach() on line 65 
     +--------------+ 
     | JOHN   | 
     +--------------+ 
+1

我甚至不知道爲什麼你正在使用的foreach()。只需迭代你的結果就可以了。 –

+0

你可以添加一個'print_r($ row)'調用並與我們分享輸出嗎? – Mureinik

+0

使用這個'$ result = mysqli_query($ connection,$ query);'兩次是多餘的。 –

回答

0

偷偷摸摸的錯字/邏輯編碼錯誤:你有一個花括號(大括號),把所有東西搞砸了。看看用來生成標題在foreach結束:

foreach($row as $key => $val){ 
    echo"<th>$key</th> "; 

這應該是:

foreach($row as $key => $val) 
    echo"<th>$key</th> "; 

然後在最後刪除虛假梅開二度。

這工作(只要至少有1列,以獲得heaedrs):

$result = mysqli_query($connection, $query); 

echo " <table >"; 

$row = mysqli_fetch_assoc($result);  

echo "<tr>"; 
foreach($row as $key => $val) 
    echo"<th>$key</th> "; 

echo "</tr>"; 

$result = mysqli_query($connection, $query); 

echo"<tr>"; 
while($row = mysqli_fetch_assoc($result)) 
{ 
    foreach($row as $key => $val) 
    { 
     echo "<td>$val</td>"; 
    } 
    echo "</tr>"; 

} 

echo "</table>"; 
+0

感謝哥們,但它並非如此! – Ng21

相關問題