2016-08-16 20 views
0

我是網絡開發新手,開始學習CRUD。來自sql查詢的PHP不完整結果表

我的問題是,雖然我成功地顯示了第1行上列出3個產品的表,但第2行上的產品no 4缺失並跳到產品no 5,並且每最後3行都丟失。

function getData(){ 
    global $connect; 
    $query = "SELECT id, name, category, price, image, info FROM product_data"; 
    $results = mysqli_query($connect, $query) or die(mysql_error()); 
    echo "<table border = 0 >"; 
    $x=1; 
    echo "<tr class='homepagetable'>"; 
    while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) { 
     if($x<=3){ 
      $x = $x + 1; 
      extract($row); 
      echo "<td class='homepagetable'>"; 
      echo "<a href=itemdetails.php?id=$id>"; 
      echo '<img src=img/' . $image . ' style="max-width:220px;max-height:240px;width:220px;height:240px;"></img><br/>'; 
      echo '<div class="truncate">'. $name .'</div><br/>'; 
      echo "</a>"; 
      echo 'Rp.'.$price .'<br/>'; 
      echo "</td>"; 
     } else { 
      $x=1; 
      echo "</tr><tr>"; 
     } 
    } 
     echo "</table>"; 
    } 

在此先感謝!

+0

修復你的html。 ''是單身標籤,''不存在。您的屬性也在引用和未引用之間醉jumping jumping的跳躍。你也不會關閉最後一排桌子,留下'​​'或其他什麼。 –

回答

1

你的問題是,你有一個錯誤的情況在這裏:

if($x <=3)... else{...} 

更改的if/else這樣:

if($x <3){$x++;} 

//...do something 

if($x == 3){ 
$x = 1; 
//Close and open tr 
} 

而且你需要關閉<img>標籤,最後<tr>在圈外標籤

0

也許你可以這樣寫:

function getData() 
{ 
    global $connect; 
    $query = 'SELECT id, name, category, price, image, info FROM product_data'; 
    $result = mysqli_query($connect, $query) or die(mysql_error()); 
    echo '<table border="0">'; 
    $x=0; 
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) 
    { 
    if($x % 3 == 0) 
    { 
     // number of articles is a multiple of 3 - so close the row 
     if($x) echo '</tr>'; // but only if there was at least 1 article 
     echo '<tr class="homepagetable">'; 
    } 
    $x ++; 
    echo '<td class="homepagetable"><a href="itemdetails.php?id='.$row['id'].'"> 
     <img src="img/'.$row['image'].'" style="max-width:220px;max-height:240px;width:220px;height:240px;"><br/> 
     <div class="truncate">'.$row['name'].'</div><br/> 
     </a>Rp. '.$row['price'].'<br/> 
     </td>'; 
    } 
    if($x) echo '</tr>'; // only close the row if there was at least 1 article 
    echo '</table>'; 
}