blue_cat blue_cat - 6 months ago 47
SQL Question

PHP only display last id number in last row

I'm trying to display 6 items in one page with 3 items in each row. And when the user click the image link it will redirect to another page and display the id however I'm having problem when the user click image it redirect to another page but it show the id of the last product in the last row of the page I'm not sure where is the mistake .. I hope you can look at my code and give me hint of were did I do that was wrong

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



}







?>

Answer

This line of code $_SESSION['id'] = $product_id; will set last product id to SESSION.(overwrites previous ids)

Try to add product id to the anchor href tag

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>";
  ......
  }

In test.php file get id by below code

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

hope this will helps you.