$_SESSION variables always printing 'S' and not intended variable when set [duplicate] - php

This question already has answers here:
MySQL query pulling one row and displaying first letter of result
(3 answers)
Closed 3 years ago.
<?php
if($_POST)
{
include 'config.php';
$referencenumber=$_POST['reference_number'];
$fullname=$_POST['full_name'];
$sRef=mysqli_real_escape_string($conn,$referencenumber);
$sName=mysqli_real_escape_string($conn,$fullname);
$query="SELECT * From customers where reference_number='$sRef' and
full_name='$sName'";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result)==1)
{
session_start();
$_SESSION['id'] = $query['id'];
$_SESSION['refnumber'] = $query['reference_number'];
header('location:index.php');
}
}
?>
The above code is what I have written on my login.php page. After a successful login, the user arrives at the index.php page.
var lz_data = {overwrite:true,111:'<?php
print_r($_SESSION['refnumber'])?>',
I am then attempting to print the reference number on the next page here, which will set a value that matches the one in $_SESSION['refnumber'] but for some reason the output of this code always seems to be 'S' when printing, just the letter S. I get the same output when I try to print $_SESSION['id'] as well. Any ideas?
EDIT: session_start(); has been added at the start of index.php, and the double quotations didn't solve the issue.

You try to get a specific index of a string instead of the result / row array:
$query="SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
$_SESSION['id'] = $query['id']; // $query is a string not an array.
$_SESSION['refnumber'] = $query['reference_number']; // $query is a string not an array.
Why you only get "S" on the session?
You can use a string value on PHP like an array. So you can use $query[0] to get the "S" and $query[1] to get the "E" and so on. In your case the $query['id'] is the same like $query[0] because var_dump('id' == 0) is true.
demo on ideone.com
How to solve this?
You can use the mysqli_result::fetch_array method to get the row with columns as index from $result:
//get the $row from $result with fetch_array.
$row = $result->fetch_array(MYSQLI_ASSOC);
//now you can use the row array to set the values to the session.
$_SESSION['id'] = $row['id'];
$_SESSION['refnumber'] = $row['reference_number'];
So your code looks like the following:
<?php
if($_POST) {
include 'config.php';
$referencenumber = $_POST['reference_number'];
$fullname = $_POST['full_name'];
$sRef = mysqli_real_escape_string($conn, $referencenumber);
$sName = mysqli_real_escape_string($conn, $fullname);
$query = "SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1) {
//get the $row from $result with fetch_array.
$row = $result->fetch_array(MYSQLI_ASSOC);
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['refnumber'] = $row['reference_number'];
header('location:index.php');
}
}

Related

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]

How to pass an random variable between php pages using $_SESSION variable?

I am trying to use variables(dates) queried in a php page then placed in $_SESSION, in another page to perform another query.
I will only use one date from that session array. which is that one i clicked on its link tag.
Is there an action that should be performed onclick of that link?
Here is my php, first page it creates the $_session variables and create the links.
The second page it is supposed to print the value i clicked. but it does not.
oldentries.php:
<?php
$query = "SELECT DISTINCT Tdate FROM titletable";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0 )
{
while($row = mysqli_fetch_assoc($result))
{
$_SESSION[$row["Tdate"]]= $row["Tdate"];
echo ''.$_SESSION[$row["Tdate"]].'<br>';
}
}
else
{
echo "No Results in the database!";
}
?>
content.php
<?php
$datetable = $_SESSION[$row["Tdate"]];
echo "$datetable";
$query = "SELECT table_name FROM information_schema.tables where table_schema='council_db'";
?>
Your $_SESSION array is keyed by the result of the SQL query. In your content.php the $row variable is not available. In cases like this it's probably better to pass variables between pages with a query parameter rather than the session.
...
while($row = mysqli_fetch_assoc($result))
{
echo ''.$row["Tdate"].'<br>';
}
...
Then in content.php you can access it with $_GET
$datetable = $_GET["Tdate"];

PHP: update variables on while statements

I am new to the PHP world! Currently practicing MySQL and PHP alone
I want to update my <p> content when my query is completed. But seems like my $name only shows the previous value:
$query = $_GET['query'];
$stmt = $conn->prepare("SELECT * FROM wordList WHERE word = '$query'");
$name = ''; // my variable
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$name == $row['word']; // not working
}
And I am not getting the actual data I want in my HTML:
<p>My name is: <?php echo $name; ?></p>
But getting:
My name is:
Thanks
Try using only one equal to symbol = instead of ==.
$name = $row['word'];

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

Categories