繁体   English   中英

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

[英]PHP incomplete result table from sql query

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

我的问题是,虽然我成功地在第一行上显示了列出3个产品的表,但是在第二行上缺少了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>";
    }

提前致谢!

您的问题是您的条件有误:

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

将if / else更改为此:

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

//...do something

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

并且您需要关闭<img>标签,并关闭循环外的最后一个<tr>标签

也许您可以这样写:

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>';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM