使用Sessions将PHP变量发送到另一个页面:

使用Sessions将PHP变量发送到另一个页面:

问题描述:

I'm having trouble with a couple of pages: I want to list all my images from a database (urls stored) and then have the user click the image which takes them to another page which then gives the rest of the information from the database.

I'm using a Session variable to send the ID of the image which is then used on the other page to select information from the database before viewing. The problem I have is that it always seems to show the last entered detail on the database and not the actual information from the variable of the image clicked.

I'm not sure where this is going wrong, I've since added plenty of session_destroy() commands which I thought was the initial problem but have not solved the issue and appear only to clog my code.

Any help or direction would be greatly appreciated.

Here's my code:

Page 1 - Sending variable through Sessions

<?php
//code to access database

$query = "SELECT * FROM releases";
$result = mysql_query($query);

if(!$result) die ("Database access failed: " .mysql_error());

$rows = mysql_num_rows($result);

  for ($j = 0 ; $j < $rows ; ++$j)

{

$row = mysql_fetch_row($result);



echo '<a href="test2.php"><img src="images/releases/' . $row[1] .'" id="' . $row [0] . '"/></a>';   
}
$id = $row [0]; //"row 0" is the auto increment of the database id.

if (isset($_SESSION ['id'])){
session_destroy();
}
session_start();
$_SESSION ['id']= $id;

mysql_close($db_server);
?>

Page 2 - Receiving the variable and then using it to access the database.

<?php

//code to access database

if (isset($_SESSION ['id'])){
    session_destroy();
}
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM releases WHERE release_id = $id";
$result = mysql_query($query);

if(!$result) die ("Database access failed: " .mysql_error());

$row = mysql_fetch_row($result);


echo    "<img src='images/events/"  .$row[1] . "' width= '150' height= '150' />    <br />";
echo    "track title: "                 .$row[2] . "<br />";
echo    "artist: "              .$row[3] . "<br />";

session_destroy();
mysql_close($db_server);
?>

Look at what your code is doing:

for ($j ...) {
   $row = mysql_fetch_row($result);
   ... do stuff with $row;
}
$id = $row[0];

you set $id AFTER the loop has terminated, meaning you will only EVER get the LAST item fetch from the query results.

Even if you were setting $id inside the loop, you'd still be only setting a SINGLE id in $_SESSION anyways:

for ($j ...) {
  $id = $row[0];
  $_SESSION['id'] = $id;
}

when the loop finishes, $_SESSION will be the last id, yet again. What you're doing does NOT need a session, just a query variable:

for ($j ...) {
   $id = $row[0];
   echo "<a href='test.php?id=$id'>click me</a>";
                          ^^^^^^^---note the query string....
}

and then in your test.php page:

$id = $_GET['id'];