来自sql查询的PHP不完整结果表

时间:2016-08-16 16:26:34

标签: php mysql

我是网络开发的新手,并开始学习CRUD。

我的问题是,虽然我成功地在第1行显示了列出3个产品的表,但在第2行中缺少4号产品,并且跳过产品号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>";
    }

提前致谢!

2 个答案:

答案 0 :(得分:1)

你的问题是你的情况有错:

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

将if / else更改为:

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

//...do something

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

您需要关闭<img>标记以及循环外的最后一个<tr>标记

答案 1 :(得分: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>';
}