create session with recordset stored in array - php

How can I take a recordset, store it in an array and then make that array the value of a session? Here is the code I came up with (with answers below integrated):
$colname_getAC = "-1";
if (isset($_GET['tech_id'])) {
$colname_getAC = $_GET['tech_id'];
}
mysql_select_db($database_localhost, $localhost);
$query_getAC = sprintf("SELECT area_code, tech_id FROM zip_zip WHERE tech_id = %s", GetSQLValueString($colname_getAC, "int"));
$getAC = mysql_query($query_getAC, $localhost) or die(mysql_error());
$row_getAC = mysql_fetch_assoc($getAC);
$totalRows_getAC = mysql_num_rows($getAC);
session_start();
// store session data
$_SESSION['area_code']= array();
while ($row_getAC = mysql_fetch_assoc($getAC)) {
$_SESSION['area_code'][] = $row_getAC['area_code'];
}
This just returns "array" though and not the area codes when I call the session.
On the session, I tried this also:
$_SESSION['area_code']= $results[];
But that just made the page stop dead in its tracks with a blank screen.
The reason for this is that I want to insert the values in this session on a different page.

You have it stored as an array, you can see it here:
var_dump($_SESSION['area_code']);
I really dont understand, what exactly you want.
Also this is wrong $_SESSION['area_code']= $results[];
EDITED:
Change your code to:
$colname_getAC = "-1";
if (isset($_GET['tech_id'])) {
$colname_getAC = $_GET['tech_id'];
}
mysql_select_db($database_localhost, $localhost);
$query_getAC = sprintf("SELECT area_code, tech_id FROM zip_zip WHERE tech_id = %s", GetSQLValueString($colname_getAC, "int"));
$getAC = mysql_query($query_getAC, $localhost) or die(mysql_error());
$totalRows_getAC = mysql_num_rows($getAC);
session_start();
// store session data
$_SESSION['area_code']= array();
while ($row_getAC = mysql_fetch_assoc($getAC)) {
$_SESSION['area_code'][] = $row_getAC['area_code'];
}

First - you must change your logic:
From this:
$results = array();
do {
$results[] = $row_getAC['area_code'];
} while ($row_getAC = mysql_fetch_assoc($getAC));
$_SESSION['area_code']= $results;
to this:
$results = array();
while ($row_getAC = mysql_fetch_assoc($getAC))
{
$results[] = $row_getAC['area_code'];
}
$_SESSION['area_code']= $results;
I've just tested - PHP has no trouble storing arrays as session variables and they are available on other pages.
BTW - you used session_start() right?
Update:
do{...}while always executes at least once as checks condition at the end
while{...} exactly the opposite (checks condition before executing code inside code block
You must use the latter here since (for example) your SQL query may return empty result (no records) so you should not execute code within while block since there is no data to get.

Related

Settings Keys from a Database as Variables in PHP

My apologies as I am sure the answer is obvious. But I am new to PHP... a transplant from ColdFusion. I have a MySQL table called settings the holds key pair values that I want to set as site-wide variables in php. For instance: page_title => 'Untitled Page', site_title => 'Sirius FireWeb'.
Here is my function that grabs the data from the database:
function get_sitesettings(){
global $db;
$sql = "SELECT * FROM settings WHERE autoload = 'yes'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;}
Here is where I call the function and thought I could loop through the query results and set the variables, but I really have no idea how to do it in PHP.
$get_settings_result = get_sitesettings();
while($settings = mysqli_fetch_assoc($get_settings_result)) {
// SET THE VARIBLES HERE USING THE QUERY OUTPUT?
}
$page_css = array();
$no_main_header = false;
$page_body_prop = array('class' => 'smart-style-1 fixed-header');
$page_html_prop = array();
Can someone please provide guidance on how to set keys as variable names in PHP?
${$settings["key"]} = $settings["value"];
But I don't think it's a good idea.
Can you try the extract() on the results?
http://php.net/manual/en/function.extract.php

php statement for multiple users not working

I am helping in some PHP design for a friends text game and have come to a stump.
I have scheduled a cron job to call the following page / following code, which is working correctly
<?php require("connect.php"); ?>
<?php
$sql = "SELECT id, name, health FROM users";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$id = htmlspecialchars($row->id);
$name = htmlspecialchars($row->name);
$health = htmlspecialchars($row->health);
$sql = "SELECT * FROM property WHERE living='1' AND ownerid='$id'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$OwnerName = htmlspecialchars($row->ownername);
$OwnerID = htmlspecialchars($row->ownerid);
$RaidPropBonus = htmlspecialchars($row->raidperc);
$RaidPropMoney = htmlspecialchars($row->raidcash);
$PropertyLvl = htmlspecialchars($row->proplvl);
$Living = htmlspecialchars($row->living);
if($PropertyLvl == '5' && $Living == '1'){
if($health < '100'){
$result = mysql_query("UPDATE users SET health=$health + '1' WHERE id='$id'")
or die(mysql_error());
} else { }
} else { }
}
}
?>
Although this only works for ONE user only. I cannot understand why this is. Any other logged in / out accounts that have met the criteria have been ignored. I can maybe only think I am missing a loop? As the ID that is being met first is number 1 and it has stopped there?
Anybody advice at all maybe?
UPDATE - It seems correct I need to get a loop in there, but am so far failing to get this loop working correct. No matter where I seem to amend / add a loop it does not help. Please may somebody suggest anything?
UPDATE2 - As requested, updated with the new version of loop
For what I've understood, the loops should be made on the mysql_fetch_object that will get the each row from the query.
Take a look at the snippet
<?php
require("connect.php");
// here prepare the $userQuery (the one that fetches all users)
// then the first loop that will read each usew row
// AFAICT this should afect all script
while($userRow = mysql_fetch_object($userQuery))
{
// prepare data fetched from the $userQuery
// prepare the $propertyQuery (the one that fetches all properties of the user)
// then the second loop to read all user property rows
// and this will afect the updates
while($propertyRow = mysql_fetch_object($propertyQuery))
{
// prepare data fetched from $propertyQuery
// add logic here
}
}
?>
Also #Matthew Carpenter had a valid point, that mysql_* is deprecated, you should consider in using mysqli_*, or in my opinion take a look at PDO

PHP/mysql fetch multiple variables in array

I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.

PHP convert session variable from array into int

I am storing session information in an array called 'Auth'. That array contains 2 session information: id and password. My problem is when I am using the id info for quering, it is not working. I am pretty sure it is due to the fact that the id info in my table is an int, and the one from the session array isn't. So my question is to know how to convert that session id variable into an int. Here below the function in which I am using $_SESSION(['Auth']['id']). Thank you in advance for your replies. Cheers. Marc
The PHP code where I am using the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
function isLogged(){
if(isset($_SESSION['Auth']) && isset($_SESSION['Auth']['id']) && isset($_SESSION['Auth']['pass'])){
extract($_SESSION['Auth']);
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = '$id' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
return true;
}
else{
return false;
}
}
}
?>
Here the PHP code where I set the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
$identifiant = mysql_real_escape_string($_POST['identifiant']);
$pass = sha1($_POST['pass']);
$result = mysql_query("SELECT * FROM users WHERE usr_pseudo = '$identifiant' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
$data=mysql_fetch_assoc($result);
$_SESSION['Auth']=array(
'id'=>$data['usr_id'],
'pass'=>$pass
);
}
echo mysql_num_rows($result);
?>
extract() is a horribly ugly function, and you should wipe its existence out of your mind.
There's no need for it, since it's purely a holdover from PHP's early "lazy" days, when it tried to do everything for you, causing in part the miserable security reputation PHP has.
You can directly embed session variables wherever you want, even when it's an arbitrarily "deep" array reference like your session is:
$sql = "SELECT ... WHERE id={$_SESSION['Auth']['id']} ...";
or even
$id = $_SESSION['Auth']['id']'
$sql = "SELECT ... WHERE id=$id";
will both work the same way, and not litter your variable namespace with useless junk.
You can cast any variable into any type by using the cast methods.
$usr_id = (int)$data['usr_id']
This would return a type of integer. If the id includes anything else but integers, 0 is returned.
http://php.net/manual/en/language.types.type-juggling.php
You should not query DB each time you'd like to check if the user is logged in. And you don't need to store password in the seesion.
You have to query db only once when you login user (your second part of the code).
And it would be better if you create a simple wrapper for your auth logic. Something like this simple class with static functions:
<?php
class Auth
{
public static function login($identifiant, $password)
{
// query db then
// $_SESSION['Auth']['id'] = value from db
return self::id();
}
public static function isLogged()
{
return (bool)self::id()
}
public static function id()
{
return (isset($_SESSION['Auth']['id'])) ? $_SESSION['Auth']['id'] : false)
}
public static function logout()
{
$_SESSION['Auth'] = array();
}
}
// usage
Auth::login($_POST['identifiant'], $_POST['password']);
if (Auth::isLogged()) {
$sql = "select * from posts where user = " . Auth::id() . "";
}
Auth::logout();
If you are "pretty sure it is due to the fact that the id info in (your) table is an int, and the one from the session array isn't".
Then here's a simple way to convert your session id from array into a variable (cast it).
$id = (int)$_SESSION['id'];
Hope it helps.
you should not enclose integers in single quotes in the SQL
try this
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = $id AND usr_pass = '$pass'");

PHP Variable - Multiply pages

I have a functions.php page, I have included in ALL my other php pages. What I want is a function in my functions.php page, I can use in all the other pages.
I have tried this:
function getSetting()
{
$r=mysql_query("SELECT * FROM settings");
if(mysql_num_rows($r) == 0)
return false;
else
$sdata=mysql_fetch_assoc($r);
return $sdata;
}
The thing I want to, I want to get the data from the row next to the name in the following picture: http://awesomescreenshot.com/0bci8x472
Example:
If I write $sdata['sitename'], I want it to output "ptcify"
Thanks!
Try using mysql_fetch_array() with MYSQL_ASSOC as documented at this link http://www.php.net/manual/en/function.mysql-fetch-array.php.
There are a lot of things you could do to further improve your code implementation i.e OOP, using better database abstraction libraries(even switching to PDO insted of PHP_MYSQL is an improvement), but this should work straight of the bat.
Most questions usually have a ? in them somewhere, to indicate an actual question. I'm not sure what the problem with your code is, but I'm guessing you're only getting a single "setting" result - if that query returns multiple rows, you have to loop over the result set and get each row, THEN return:
$r = mysql_query(...) or die(mysql_error());
$sdata = array()
while ($row = mysql_fetch_assoc($r)) {
$sdata[] = $row;
}
return $sdata
edit
$sql = "SELECT setting_name, setting_value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
$sdata = array();
while($row = mysql_fetch_assoc($result)) {
$sdata[$row['setting_name']] = $row['setting_value'];
}
return $sdata;

Categories