I am a complete beginner who has been "experimenting" with PHP for quite some time.
Actually I’m very proud of my achievement so far, but slowly but surely I’m also doubting myself, I have the following code on page no. 1 place.php
<?php
session_start(); // Starte die Sitzung
$con = mysqli_connect("localhost", "root", "", "vmaxdbweb");
$res = mysqli_query($con, "SELECT * FROM tblplatz");
// Tabellenbeginn
echo "<table class='tbl'>";
// Überschrift
echo "<th>ID</th> <th>Bezeichung</th> <th>Code</th>";
echo "<th>Notizen & Beurteilung</th> <th>Geodaten</th> <th>Details</th>";
$lf = 1;
while ($dsatz = mysqli_fetch_assoc($res))
{
// Speichere die Daten in der Sitzung mit dem Schlüssel 'pla_id'
$_SESSION["detail"] = $dsatz["pla_id"];
echo "<tr>";
echo "<td>" . $dsatz["pla_id"] . "</td>";
echo "<td>" . $dsatz["pla_bezeichnung"] . "</td>";
echo "<td>" . $dsatz["pla_code"] . "</td>";
echo "<td>" . $dsatz["pla_notiz_beurteilung"] . "</td>";
echo "<td>" . $dsatz["pla_geodaten"] . "</td>";
echo "<td><a href='content/placedetail.php'>Details</a></td>";
$lf = $lf + 1;
}
// Tabellenende
echo "</tabelle>";
mysqli_close($con);
?>
<table>
</table>
on page 2 placedetail.php I have this code
<?php
session_start();
// Hole den Wert der `pla_bezeichnung`-Spalte aus der Sitzung
$pla_bezeichnung = $_SESSION["detail"];
// Zeige die Details des jeweiligen Platzes an
echo "Der Platz heißt " . $pla_bezeichnung;
?>
A value is also passed, but no matter which link I click in the table, it is always only a value from the last data record in the table. Go crazy slowly but surely.
I already found that the value is always overwritten because it’s in a loop. How can I position the session better?
I’ve tried everything so far
2
Answers
It’s because you put the last value intoyou session variable in the line below:
if you want to keep all IDs in session you need to put all $dsatz["pla_id"] in an array and then pass array to $_SESSION["detail"].
To do this outside of while write:
Then inside while loop:
Array_push($_SESSION["detail"],$dsatz["pla_id"])
;But i believe this is not a optimal way to do this, because you need to search array again in the page 2.
A better way would be to pass IDs to each row elements onclick, then create a http request and pass it to you page 2.
Your problem is that during the
while
loop,$_SESSION["detail"] = $dsatz["pla_id"];
overwrites the session value at each iteration of the loop. So by the time you click to go to placedetail.php, the Session contains whatever was the last value which the loop processed.But I don’t see why you are using the Session here, it doesn’t really make sense. If you want the placedetail.php to show a particular record, you should follow these steps:
place.php:
placedetail.php