2013-12-16 125 views
0

我有一些麻煩,我的第一個PHP項目,我試圖從MySQL數據庫(有3條記錄)獲取數據並將其顯示在表中。問題是它似乎只顯示記錄2和3,它跳過第一條記錄。請參閱我的代碼並在下面顯示。在表中顯示記錄

if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$result = mysqli_query($con,"SELECT * FROM unitstats"); 

while($row = mysqli_fetch_array($result)) { 
    echo "<table border='1' style='color:white'> 
    <tr> 
    <th>ID</th> 
    <th>Name</th> 
    </tr>"; 

    while($row = mysqli_fetch_array($result)) { 
    echo "<tr>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" . $row['name'] . "</td>"; 
    echo "</tr>"; 
    } 
    echo "</table>"; 
} 

enter image description here

+0

什麼是第一個'while'在做什麼? – Salman

+0

'while($ row = mysqli_fetch_array($ result))'我不認爲你知道這是什麼T.T – hanzo2001

+0

爲什麼所有的答案都被低估? – user2936213

回答

1

你這是不必要的使用下面的循環利用,同時兩個代碼

if (mysqli_connect_errno()) 
     { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
     } 

     echo "</table>"; 


echo "<table border='1' style='color:white'> 
<tr> 
<th>ID</th> 
<th>Name</th> 
</tr>"; 
$result = mysqli_query($con,"SELECT * FROM unitstats"); 

while($row = mysqli_fetch_array($result)) 
    { 


echo "<tr>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" . $row['name'] . "</td>"; 
    echo "</tr>"; 
} 
    echo "</table>"; 
+0

是這個答案不同,其他人給了這裏?爲什麼這是upvoted和否則所有其他人都會被低估? – user2936213

+0

@ user2936213問他們誰高舉這個答案。你有沒有看到這個答案也被問題所有人接受? –

+0

它不僅適合你,還會有人在做這些東西。他只是試圖讓我們所有的人都沒有任何理由的聲譽。 – user2936213

1
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

echo "<table border='1' style='color:white'> 
<tr> 
<th>ID</th> 
<th>Name</th> 
</tr>"; 

$result = mysqli_query($con,"SELECT * FROM unitstats"); 

while($row = mysqli_fetch_array($result)) 
{ 
    echo "<tr>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" . $row['name'] . "</td>"; 
    echo "</tr>"; 
} 
    echo "</table>"; 

基本上你並不需要的初始循環,這將有因爲你已經與第二循環重新聲明$row主要是一個問題。

0

只是刪除你的外循環時,只是使用:

if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$result = mysqli_query($con,"SELECT * FROM unitstats"); 


echo "<table border='1' style='color:white'> 
<tr> 
<th>ID</th> 
<th>Name</th> 
</tr>"; 

while($row = mysqli_fetch_array($result)) { 
    echo "<tr>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" . $row['name'] . "</td>"; 
    echo "</tr>"; 
} 
echo "</table>";