PHP Session for an Array is not working? - php

I have an array which I have put into a SESSION, but for some reason when I click a button on the page, instead of the list of items showing again using the id numbers from the array stored in the session, it returns to main.php (which is what I have told it to do when it isn't set)
$games= $_POST['games'];
if (!empty($games)){
$_SESSION["gamelist"] = $games;
$list = implode(',', $games);
}else {
header('Location:./main.php');
}
Printing the result out is the code:
$conn = pg_connect("host=*** port=*** dbname=*** user=*** password=*****");
$sql = "SELECT column1, column2, column3 FROM table WHERE Id IN ($list)";
$result = pg_query($conn, $sql);
Any help would be amazing, thanks.

Uhm, you are checking the content of $_POST['games'], which is obviously not a session variable.

I can't see where you are retrieving data from the session variable. I only see you set it. $list needs to come from your session variable if it exists, and not just from your $_POST variable.
$games= $_POST['games'];
if (!empty($games)){
$_SESSION["gamelist"] = $games;
}else {
header('Location:./main.php');
}
if ( isset( $_SESSION['gamelist'] ) ) $games = $_SESSION['gamelist'];
$list = implode(',', $games);

Related

select query inside for each loop of PHP is not working

Good day! I am trying to get the user ids based on the names submitted on the input field. But the loop only returns the user id of the first selected user. Can somebody please help me?
Here's the code:
if(isset($_POST['proponent'])){
$proponent = mysqli_real_escape_string($con,$_POST['proponent']);
$myArray = explode(',', $proponent);
$posts = array();
foreach($myArray as $item) {
$query = "SELECT user_id FROM user WHERE CONCAT(fname, ' ', lname) = '$item'";
$get = mysqli_query($con, $query);
array_push($posts, mysqli_fetch_assoc($get));
print_r($posts);
}
}
Using mysqli_fetch_assoc only once will only get you the first row if it exists. So you will need to add this in a loop, say while loop like below in order for the mysqli_function to move it's pointer over the entire result set.
while($row = mysqli_fetch_assoc($get)){
$posts[] = $row;
}

Storing database results to a variable in PHP

I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]

Trying to insert data from sql to cookies

Trying to insert multiple "ids" into cookie from mysql database. So, i am pressing a few links and collect their ids in an array. And then trying to implode this array and give it to a function, which should take an info from sql database and write it down to cookie $basket.
But in showbasket.php i've got only one, last pressed id. The main problem is in ids i think, but i can't figure it out.
p.s. this is just a cookie-training, not a real implementation.
this is a file add2basket.php:
<?php
require 'functions.php';
$id = $_GET['id'];
$arr = [];
$arr[]=$id;
$ids = implode(",", $arr);
save2basket($ids);
header("Location: catalog.php");
?>
This is a function save2basket:
function save2Basket($ids){
global $conn, $basket, $ids;
if(!isset($_COOKIE['basket']))
$basket = setcookie('basket', $sel);
$sql = "SELECT * FROM catalog WHERE id IN ($ids)";
$result = mysqli_query($conn, $sql);
$select = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_free_result($result);
$sel = base64_encode(serialize($select));
$basket = setcookie('basket', $sel);
}
This is a showbasket.php file:
<?php
$basket = unserialize(base64_decode($_COOKIE['basket']));
print_r($basket);
Replace your PHP code with below code. You should have to save your selected ids in session. Currently each time php page will called your array will be initialized blank and it will contain only recent id. Don't forget to unset session after your entire operation get complete.
<?php
session_start();
require 'functions.php';
$id = $_GET['id'];
$_SESSION['arr'] = $id;
$ids = implode(",", $_SESSION['arr']);
save2basket($ids);
header("Location: catalog.php");
?>

How to print multiple ID's from a $_GET variable using while() and array()

I'm here today because i'm under a minor issue that i can't seem to solve and it's why it brings be here.
The issue is that i'm trying to get multiple ID's from a $_GET variable to print out. I tried to use array and great, it works but the thing is it makes separate arrays with [0] and i need it to be as one in the same array not array() array() which is what its doing.
So i'm using while() with mysql_fetch_array to get the results off the database and it depends on the $_GET from the url in-order to grab the correct id's. So in the URL i pass in api.php?do=remove&id=1,4,7 it will only print out the first id and not the others as a name. As i said i tried with array() and this is what came out :
Array
(
[0] => BzlXO.jpg
)
Array
(
[0] => cHZTk.jpg
)
Array
(
[0] => 9yset.jpg
)
Array
(
[0] => Ss04V.jpg
)
i don't understand why its doing that as i need it to be in one array as in
Array (
[0] => BzlXO.jpg,
[1] => cHZTk.jpg,
[2] => 9yset.jpg,
[3] => Ss04V.jpg
)
So that way when i implode them it will show as text as in:
"You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
with something like
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
Here is my code:
This is the URL "api.php?do=remove&id=1,4,7"
$ID = $_GET['id'];
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
$api_message = "You removed image(s) $name";
}
}
The OUTPUT :
You removed image(s) BzlXO.jpg
but i need it to be:
The OUTPUT :
You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
Any help with this will be much appreciated, if any more information is needed please let me know and i'll include
Thanks
In addition to the solution posted by raina77ow, there is also a problem with the control flow in that you are executing the DELETE FROM uploads WHERE ID IN (...) statement for each iteration of the while loop. This will delete all the records on the first iteration. You need to change it to something like:
$ID = $_GET['id'];
$names = array();
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID = {$iName['ID']} AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$names[] = $iName['imagename']);
}
}
$name = implode(",", $names);
$api_message = "You removed image(s) $name";
Perhaps you need to fill an array declared before the loop instead, like that:
$images = array();
while( $iName = mysql_fetch_array($result)) {
...
$images[] = $iName['imagename']; # pushing the deleted image into that array
}
...
$names = implode(', ', $images);
And I strongly suggest at least checking the possibility of using mysqli set of functions instead (or PDO, that's even better in my opinion, but might be a step too huge for your codebase). )
You should revise your code as to protect it against invalid values and reduce the possibility of failures.
As to your specific problem, there's no need to place values from one array inside another one, just to the goal of imploding it to a string. You can simply use string concatenation to keep adding the desired values.
This suggestion fixes you issue: code comments are to explain whats happening
// initialize the user message with the success string
$api_message = "You removed image(s): ";
// check if the URL variable exists and contains values
if (isset($_GET['id']) && $_GET['id']!='') {
// clean the values a litle bit to prevent code injection
$ID = strip_tags(trim($_GET['id']));
// prepare the query (more compatible string concatenation)
$query = "SELECT ID, imagename FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
// query the databse
$result = mysql_query($query);
// check for results
if (is_resource($result) && mysql_num_rows($result)>=1) {
// get total records
$counter = mysql_num_rows($result);
// run by each result found
while($iName = mysql_fetch_array($result)) {
// delete all from the database
$querys = "DELETE FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
$results = mysql_query($querys);
// check if the returned result is false
if (!$results) {
// replace the user message with a fail information
$api_message = 'Failed to get a Removal result';
} else {
// decrease the counter
$counter--;
// update the user message and add a "," if this is not the last name
$api_message.= $iName['imagename'] . (($counter==0)?(''):(', '));
}
}
} else {
$api_message = 'ups... failed to talk with the database';
}
} else {
$api_message = 'ups... no ids collected';
}
Related reading:
PHP strip_tags
strip_tags — Strip HTML and PHP tags from a string
PHP trim
trim — Strip whitespace (or other characters) from the beginning and end of a string
PHP is_resource
is_resource — Finds whether a variable is a resource

Serializing the $_SESSION and storing it in a mySQL table

I'm trying to store my session in a database. I can serialize it and insert it into a TEXT field in a table. I can also pull it back out and 'unserialize' it. I cannot seem to get it back into my session.
I basically want to grab it from the table, and replace my $_SESSION with it, so all the values of the session will be available again like this $_SESSION['somevalue'].
I serialize it:
if(!empty($_POST)){
unset($_POST['submit_x'],$_POST['submit_y'],$_POST['submit']);
foreach ($_POST as $key=>$value) {
$_SESSION[$key] = $value;
}
$serialized_data = serialize($_SESSION);
setSession($userID,$serialized_data);
}
and then save it:
function setSession($userID,$data){
//is there a row?
if(getSession($userID)){
$sql = "UPDATE session_data SET session = '".mysql_real_escape_string($data)."' where user_id = ".$userID;
}else{
$sql = "INSERT into session_data VALUES('',".$userID.",'".mysql_real_escape_string($data)."')";
}
$result = mysql_query($sql) or die(mysql_error());
return $result;
}
and then I come to the part where I need to replace my $_SESSION with it.
foreach(unserialize($serialized_data) as $key=>$value){
$_SESSION[$key] = $value;
}
Can I not put it into a foreach like this? I'm stumped and not really sure which stage I'm going wrong at.
you can use JSON instead of serialize (deep level is guarantee)
$dbstring = json_encode($_REQUEST);
$_REQUEST = json_decode($dbstring, true);

Categories