PHP $_SESSION only store the last variable - php

Thank you for reading this, I am building a shopping cart with PHP session, when I click the submit button on the form, the $_POST was able to pass the value to the $_SESSION[''] array, but when I click the submit button again, the $_SESSION array only contain my last $_POST variable and the previous variables are all gone. As a shopping cart, the session array suppose to contain every data obtain from the POST value.
I checked with the SESSION_ID, which was able to shows the same ID when I submit the form, the var_dump shows the current SESSION array works (except only showing the last item). Please help me what is wrong in my code in order to keep the value into the SESSION array, thank you.
here is the full code, the sqli_query was replaced to specify item_id for troubleshooting, also this php will be included in another php that have an id in url, which seems irrelevant to this matter, but just for your information.
<?php if(!isset($_SESSION)){session_start();}?>
<?php
//if(isset($_GET['id']) && !empty($_GET['id'])){
require 'connecttosql.php';
$result = mysqli_query($con,"select COLOUR_EN, COLOUR_ZH, SIZE FROM mydb.item join mydb.colour using(item_id) join mydb.size using(item_id) WHERE ITEM_ID='T76'")
or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$size[] = $row['SIZE'];
$colour_zh[] = $row['COLOUR_ZH'];
$colour_en[] = $row['COLOUR_EN'];
}
mysqli_free_result($result);
mysqli_close($con);
for($x=0;$x<count($colour_zh);$x++){
$colour[$x] = $colour_zh[$x] . "/" . $colour_en[$x];
}
echo "<form action='' method='POST'>";
echo "<ul>";
echo "<li>size: </li>";
echo "<li><select name = 'size'>";
foreach(array_unique($size) as $sizeli){
echo "<option value = '" . $sizeli . "'>" . $sizeli . "</option>";
}
echo "</select></li>";
echo "<li>colour: </li>";
echo "<li><select name = 'colour'>";
foreach(array_unique($colour) as $COLOURli){
echo "<option value = '" . $COLOURli . "'>" . $COLOURli . "</option>";
}
echo "</select></li>";
echo "<li><input type='SUBMIT' name='submit' value='ADDTOCART'></li>";
echo "</ul>";
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
if(isset($_POST['submit'])) {
$_SESSION['size'][] = $_POST['size'];
$_SESSION['colour'][] = $_POST['colour'];
// $_SESSION['id'] = $_GET['id'];
}
echo SESSION_ID();
var_dump($_SESSION['size']);
var_dump($_SESSION['colour']);
// var_dump($_SESSION['id']);
/*
}else{
include 'index.php';
die();
}
*/
?>

You reinitialize (and therefore reset) the arrays at every request:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
Add a check like this:
if(!isset($_SESSION['size'])) {
$_SESSION['size'] = array();
}
if(!isset($_SESSION['colour'])) {
$_SESSION['colour'] = array();
}

it looks like you are resetting your session variables before it gets to this line...
if(isset($_POST['submit'])) {
try checking for existance of these before resetting...
$_SESSION['size'] = array();
$_SESSION['colour'] = array();

While doing this:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
you are doing a reset to $_SESSION['size'] and $_SESSION['colour'].
You can replace it with:
if(empty($_SESSION['size'])) $_SESSION['size'] = array();
if(empty($_SESSION['colour'])) $_SESSION['colour'] = array();
or just delete these two entries.

Related

Is there any way to pass SESSION id through the anchor tag when the user clicks on it?

I want to pass a unique session for each link that user clicks on, something like this:-
$sql = "select * from modulestb where teacherid=?";
$st = $pdo->prepare($sql);
$st->execute(array($_SESSION['logid']));
foreach ($st as $row) {
$_SESSION['stage'] = $row['stage'];
$_SESSION['mid'] = $row['mid'];
echo "<a style='color:white;' href=report.php?>" . $row['name'] . " (Stage :" . $row['stage'] . "</a>";
}
As an example:
I haven't tested this code but I hope you understand the concept :-)
<?php
//Always use this preferbly at the start of the script
//when dealing with sessions in PHP
session_start();
//If data isset and contains anything
if (!empty($_GET['data'])) {
$data = unserialize($data); //Restore to the array
$id = $data['mid'];
//Set the actual session based on what user has clicked on
//If user has clicked on mid 1 , this will store $_SESSION['module1'] = value of stage
//If user has clicked on mid 2 , this will store $_SESSION['module2'] = value of stage
//etc
$_SESSION['module'.$id] = $data['stage'];
}
$sql = "select * from modulestb where teacherid=?";
$st = $pdo->prepare($sql);
$st->execute(array($_SESSION['logid']));
foreach ($st as $row) {
//Serialize the data you want to save into your session
//(Make the array a string that represents the array)
$data = serialize(array('stage'=>$row['stage'],
'mid' => $row['mid']));
echo "<a style='color:white;' href=report.php?data=$data>" . $row['name'] . " (Stage :" .
$row['stage'] . "</a>";
}

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();

Updating multiple SQL records using a single submit button

Scenario: I have multiple text boxes in which a user will enter data into some of them / all of them / or none of them.
Goal: I need to be able to UPDATE multiple records based on what is in the text boxes where the users has entered their data.
Problem: The update statement is not working when I try to update each record for each text box.
Below is the code:
$conn = mysql_connect ($localhost, $user, $pass);
mysql_select_db($db_name, $conn) or die (mysql_error());
$myFile = "/var/www/html/JG/LSP/lsp_ref.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
if (isset($_POST['submit'])) {
foreach ($_POST['notes'] as $key=>$value) {
echo $_POST['notes'][$key];
#echo "<br/>";
//echo "$key";
//echo "<br/>";
$query_update = "UPDATE lsp_active SET Notes = ".$_POST['notes'][$key];
$result_update = mysql_query($query_update);
}
#header ('Location:lsp_display.php');
}
$query = "SELECT * FROM lsp_active";
$result = mysql_query($query);
$field_num = mysql_num_fields($result);
echo "<form method='post' action='lsp_display.php'>";
echo "<table border=1>";
$cols = 0;
while ($row = mysql_fetch_assoc($result)) {
if ( $cols == 0) {
$cols = 1;
echo "<tr>";
foreach ($row as $col => $value) {
print "<th>$col</th>";
}
print "<th>Insert Ticket / Notes</th>";
echo "</tr>";
}
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "<td><input type='text' name='notes[]'/></td>";
echo "</tr>\n";
}
echo "<tr><td colspan=8><input type='submit' name='submit' value='Update'/></td></tr>";
echo "</form>";
mysql_free_result($result);
?>
Now when I print out $_POST['notes'][$key] it spits back out what I give it in the text boxes.
However, the update statement that I have for my SQL isn't updating the database with what I put in.
I am not sure what could be wrong with it :(.
Any help is appreciated!
Thank you!
It looks like you probably need to surround your $_POST in single quotes.
Also use a function to clean the $_POST variable.
For example:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
And then your query:
$query_update = "UPDATE lsp_active SET Notes = '" . escape($_POST['notes'][$key]) . "'";
Edit:
You also might want to put a WHERE statement on the end of your UPDATE query, so that you don't update everything in the table.
"UPDATE lsp_active a SET a.Notes = '" . mysql_real_escape_string($_POST['notes'][$key]) ."' WHERE a.Index = '" . ($key + 1). "'"
Index is a keyword thar refers to indexes, not your column. So I defined an alias, and made it explicit that Im referring to the column. Also, the + 1 on the Where $key since Index is not zero-based like PHP arrays.

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