PHP仅显示最后一行中的最后一个id号

PHP仅显示最后一行中的最后一个id号,php,sql,Php,Sql,我试图在一页中显示6项,每行显示3项。当用户单击图像链接时,它将重定向到另一个页面并显示id。然而,当用户单击图像时,它确实会重定向到另一个页面,但它会在页面的最后一行显示最后一个产品的id,这是不正确的。我不确定我是在哪里犯的错误。我希望你能看看我的代码,给我一个错误所在的提示 <?PHP session_start(); function connect() { $servername = xxxxxxxx; $username = xxxxxxxx;

我试图在一页中显示6项,每行显示3项。当用户单击图像链接时,它将重定向到另一个页面并显示id。然而,当用户单击图像时,它确实会重定向到另一个页面,但它会在页面的最后一行显示最后一个产品的id,这是不正确的。我不确定我是在哪里犯的错误。我希望你能看看我的代码,给我一个错误所在的提示

      <?PHP
session_start();

function connect()
{
    $servername = xxxxxxxx;
    $username   = xxxxxxxx;
    $password   = xxxxxxxx;
    $dbname     = xxxxxxxx;

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn) {
        echo 'connection is invalid';
    } else {
        mysqli_select_db($conn, "mytest");

    }

    return $conn;
}

function getData()
{
    $conn = connect();

    if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
        $startrow = 0;
    } else {
        $startrow = (int) $_GET['startrow'];

    }

    $sql = "SELECT * FROM tbl_products LIMIT $startrow, 6";
    $getdata = mysqli_query($conn, $sql) or die(mysqli_error());


    $cell_img = mysqli_num_rows($getdata);

    $i       = 0;
    $per_row = 3;
    echo "<table id='productTumb'><tr id='proRow'>";
    $data = '';
    while ($row = mysqli_fetch_assoc($getdata)) {
        //echo "<a href='ProDet.html'></a>";
        echo "<td><a href='test.php'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
        $data .= "<td style='background-color:#FF0004'>" . $row['product_name'] . "</td>";
        $product_id = $row['products_id'];

        $_SESSION['id'] = $product_id;
        if (++$i % $per_row == 0 && $i > 0 && $i <= $cell_img) {
            echo "</tr><tr>$data</tr><tr>";
            $data = '';




        }
    }

    for ($x = 0; $x < $per_row - $i % $per_row; $x++) {


        echo "<td></td>";


    }

    echo "</tr>";
    echo "</table>";


    echo '<a href="' . $_SERVER['PHP_SELF'] . '?startrow=' . ($startrow + 5) . '">Next >>></a>';
    $prev = $startrow - 5;
    if ($prev >= 0)
        echo '<a href="' . $_SERVER['PHP_SELF'] . '?startrow=' . $prev . '"> <<<< Previous</a>';



}







?>

这行代码$\u SESSION['id']=$product\u id;将最后一个产品id设置为会话。(覆盖以前的id)

尝试将产品id添加到锚href标记

while ($row = mysqli_fetch_assoc($getdata)) {
  echo "<td><a href='test.php?id=".$row['products_id']."'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
  ......
  }

希望这能对您有所帮助。

请格式化您的代码,使其更具可读性。@Justinas很抱歉代码凌乱。您是如何在test.php页面中获取产品id的?使用$_SESSION['id']?@ravindereddyyah我使用$pid=$_SESSION['id'];echo$pid;我写的是同样的答案:)@Peter的想法也一样:)
 if(isset($_GET)){
  $pid = $_GET['id']; 
  echo $pid;
 }