Sending PHP variables to another page using 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 '<img src="images/releases/' . $row[1] .'" id="' . $row [0] . '"/>';
}
$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'];

Related

using fetch twice in php to get the data

I'm trying to get a data from db, I would to say welcome $row['name'];
then in a loop need to print the items
if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?
is there a way to use this $row = $SQL->fetch() for both?
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$row2 = $SQL->fetch();
echo "Welcome " . $row2['name'] . "<br>";
while ($row = $SQL->fetch()) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
}else{
echo "<h1>Not Logged in. Access denied.</h1>";
}
?>
When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.
Probably the easiest approach would be to pull all results into an array and then work with that.
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$data = $SQL->fetchAll();
$row2 = $data[0];
echo "Welcome " . $row2['name'] . "<br>";
foreach ($data as $row) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
} else {
echo "<h1>Not Logged in. Access denied.</h1>";
}

My Sessions Keeps Sending a Fixed Value while it's supposed to be changeable

Well i got this script
while($row = $result->fetch_assoc()) {
$_SESSION["sup"] = $row['id'];
if ($hi < $row['buytime']) {
} else {
echo " <form action='Action1.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='Action.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
The only problem is hat in line $_SESSION["sup"] = $row['id'];
Keeps sending a fixed value which it's 144 while the $row['id']; is not a fixed value , i'm really lost lol
If session is a bad idea , how can i send ID to action.php without inserting the ID in a hidden input ?
Update the two pages
First PAge
<?php
$conn = mysqli_connect("localhost", "localhost", "localhost", "localhost");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$buyer = $_SESSION['username'];
$sql_shells = "SELECT buytime,id,situation,buyer FROM shells WHERE situation = 'sold' AND buyer = '$buyer' ";
$dt = new DateTime();
$dt->modify('+172799 seconds');
$hi = $dt->format('Y-m-d H:i:s');
$_SESSION["sup"] = [];
$result = $conn->query($sql_shells);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
if ($hi < $row['buytime']) {
}else{
echo " <form action='view_item.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='reportinsert.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
}else {
}
?>
Second page
<?php
session_start();
if (isset($_SESSION['username'])) {
$link = mysqli_connect("localhost", "localhost", "localhost", "localhost");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$trn_date = date("Y-m-d H:i:s");
$seller = $_SESSION['username'];
$id = $_POST['whatever'];
$id = explode(',', $id); // You now have an array of IDs.
$sql = "INSERT INTO reports (reporter,stats,trn_date,itemid) VALUES ('$seller','Opened','$trn_date','$id')";
if(mysqli_query($link, $sql)){
echo $id;
echo $seller;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
} else
{
header("location:/quickshops/login.php");
}
?>
now it gives me Array in insert
Remove inside $row '' from $row['id'].
You will always get the last row's value, the reason is, you set the session in each iteration so whenever you plan to use it out of the loop, you will get the value of last iteration.
In case you want to set the array within the session, that's how you can do that:
$idsArray= array();
while($row = $result->fetch_assoc()) {
$idsArray[] = $row['id'];
}
$_SESSION["ids"] = $idsArray;
You are rewriting the value every time you go through the loop:
// loop through results
while($row = $result->fetch_assoc()) {
// overwrite session variable with the last id
$_SESSION["sup"] = $row['id'];
So if you have 10 results, the session var will be the id of the 10th row.
Without more detail on what you are trying to achieve with your result set, we can't really help much more than that. Maybe update your question with more details if this isn't enough to solvce your problem?
Update Ok so you need ALL Id's
You could make the session var an array, and when it's time to post the ID's, implode() them with a comma. Then in the receiving script, explode on a comma to get all the ids.
$_SESSION["sup"] = [];
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
// etc
}
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
And in the other script
$ids = $_POST['whatever'];
$ids = explode(',', $ids); // You now have an array of IDs.
Incidentally, since you are using a session variable, you probably don't even need to post it, and just access the session in the other script, but then I've no idea what your code is doing

php insert to database row id and session id when click a button

How do I insert to the database when you click a button?
I also need to insert in the same command, the row [id] and SESSION [id]
I use an html page that calls the php, then the variaves SESSION are not in my php page. I'm stuck here .. please help
<?php
session_start();
if(!isset($_SESSION["email"]) || !isset($_SESSION["senha"])) {
header("Location: login.php");
exit;
}
?>
<?php
$deets = $_POST['deets'];
$deets = preg_replace('#[^0-9/]#i', '', $deets);
include ("connect.php");
$events = '';
$query = mysql_query('SELECT hora, status FROM horario');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button class="btn2" style=" float:right;" onMouseDown="overlay()"><b>Fechar</b></button><p><b> ' . $deets . '</b></p></div> <br />';
while($row = mysql_fetch_array($query)) {
$desc = $row['hora'];
$desc1 = "<input type='submit' class='btn1' name='insert' value='Marcar Hora' />";
$events .= '<div id="eventsBody">' . $desc . ' | '.$desc1. '<br /><hr><br /></div>';
}
}
echo $events;
if(isset($_REQUEST['insert']))
{
$SQL = "INSERT INTO eventos (id, data, idhora,) VALUES ('', '.$deets.', '$row[id]', 'session[id]')";
$result = mysql_query($SQL);
}
?>
2 Problems I initially see, although I don't have full context of your code.
First, I don't see you starting the session anywhere, this requires you to run session_start(); before you try to grab the session ID or save any variables into the session.
Second, as far as I understand it you'll need to reference the session id by doing something like this.
$id = session_id();

using dynamic data in a javascript method

I'm new at php and JavaScript so I hope you can help me!
below is a php code! it take data from my db and display my photos and photo's title. what I want to do is if you click on one of this photos and than a new php expe: photo.php opens and you can see the same photo alone not with the other ones.
<?php
$link = mysql_connect("localhost", "root","");
mysql_select_db("test", $link);
$query = "select * from post order by id DESC;";
$results = mysql_query($query, $link) or die ("you comand can't be executed!".mysql_error());
if($results){
$i = 1;
while ($row = mysql_fetch_assoc($results)){
echo $row['title']. "<img src=/1/" . $row['location']. " width=580px > " . "<br /><br /><br />";
}
}
?> '
<?php
$link = mysql_connect("localhost", "root","");
mysql_select_db("test", $link);
$query = "select * from post order by id DESC;";
$results = mysql_query($query, $link) or die ("you comand can't be executed!".mysql_error());
if($results){
$i = 1;
while ($row = mysql_fetch_assoc($results)){
//send photo_id (id of photo from your table) from url NOTE: I've put link here
echo $row['title']. "<a href='index.php?photo_id=".$row['id']."'><img src=/1/" . $row['location']. " width=580px ></a> " . "<br /><br /><br />";
}
if(isset($_GET['photo_id'])) {
//here you get only one id of photo now retrieve the data from database and display the image
}
}
?>
You will get the photo by the help of the url value here photo_id.
do this way you are getting results from database and you are
displaying them with tile and image your aim is to click on
image or image title go to a new page and display image alone
the image title as link in first page
if($results){
$i = 1;
while ($row = mysql_fetch_assoc($results)){
<a href='new page url?id=<?php echo $row["id"] ?>'>
echo $row['title'];
echo "</a>"
}
}
where $row['id'] is database unique id if have no it is always preferred
to create a database with unique id and in new page get the uid
using $id=$_GET['id'] and
do as below
if($results){
$i = 1;
while ($row = mysql_fetch_assoc($results)){
if($id==$roe['id']{
echo $row['title']. "<img src=/1/" . $row['location']. " width=580px > ";
}
}
}

PHP not be able to echo data [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP not be able to echo data
I'm trying to get data from database, and echo them on the page using their unique id.. below is my code
<?php
session_start();
require_once('config.php');
//create query statement
$query = 'SELECT * FROM player_info';
//make the query from db
$myData = mysql_query($query, $conn)
OR exit('Unable to select data from table');
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
}
?>
and here is how i code for echo the data
<?php
if ($playerID == 1)
{
echo '<p class="playerAchievesL">' . $achievements . '</p><p class="playerInfoL">' . $player_bio . '</p>';
}
?>
I don't get any error return from php, but the data does not display anything... help please ... thank you so much
If I understand correctly, you need to place the echo inside the while() loop:
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
echo '<p class="playerAchievesL">' . $achievements . '</p><p class="playerInfoL">' . $player_bio . '</p>';
}
You fetch all players from the table, and for each player, overwrite $playerID, $player_bio and $achievements. After the while loop, $playerID contains the identifier of the last fetched player.
If you have more than one player, this most likely is not $playerID with 1.
problem is in here. you're overwriting the values on every iteration
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
$playerID = $row['id'];
$player_bio = $row['player_bio'];
$achievements = $row['player_achts'];
}
Just echo them directly in the loop:
while($row = mysql_fetch_array($myData, MYSQL_ASSOC)){
echo $row['id'];
echo $row['player_bio'];
echo $row['player_achts'];
}
Your while loop may be overwriting $pkayerID, so if the last playerID isn't 1 the it won't echo anything.
Try putting the echo line after the $achievemets line to see if this is the case.

Categories