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

时间:2016-05-19 14:40:51

标签: php sql

我试图在一个页面中显示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>';



}







?>

1 个答案:

答案 0 :(得分:3)

这行代码$ _SESSION [&#39; id&#39;] = $ product_id;将最后的产品ID设置为SESSION。(覆盖以前的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>";
  ......
  }

在test.php文件中,通过以下代码获取id

 if(isset($_GET)){
  $pid = $_GET['id']; 
  echo $pid;
 }

希望这会对你有所帮助。