PHP - Mysql Query Vs. Session / Get Vs Session?
Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. Similar TutorialsI'm restarting this under a new subject b/c I learned some things after I initially posted and the subject heading is no longer accurate. What would cause this behavior - when I populate session vars from a MYSQL query, they stick, if I populate them from an MSSQL query, they drop. It doesn't matter if I get to the next page using a header redirect or a form submit. I have two session vars I'm loading from a MYSQL query and they remain, the two loaded from MSSQL disappear. I have confirmed that all four session vars are loading ok initially and I can echo them out to the page, but when the application moves to next page via redirect or form submit, the two vars loaded from MSSQL are empty. Any ideas? I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I need help making $_SESSION['code'] match variable $code when executed. They're both accessing rand() but with different results. Code: [Select] <?php function create_user($params) { db_connect_posts(); $code = rand(11111111,99999999); $_SESSION['code'] = $code; $query = sprintf("INSERT INTO users SET users.screen_name = '%s', users.user_email = '%s', users.user_pwd = '%s', users.image = '%s', created_at = NOW(), users.code = $code, users.active = '0'" , mysql_real_escape_string($params['screen_name']), mysql_real_escape_string($params['user_email']), md5($params['user_pwd']), mysql_real_escape_string($params['image']) ); $result = mysql_query($query); if(!$result) { return false; } else { return true; } } ?> I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content. To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> Hello all, I've made this for users login, and now I want the user to only be able to see his info so how can I use the $_SESSION['userid'] to search the database for it's value and echo results? here is my code, I want to use the session value instead of get Code: [Select] <? if (isset($_GET['id'])) { $con = mysql_connect("supremecenter14.co.uk","teko_waw","tmisabro77"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("teko_waw", $con); $result = mysql_query("select * from users where id = '{$_GET['id']}'"); $row = @mysql_fetch_array($result); echo "<table width=98%>"; echo "<tr>"; echo "<td valign=\"top\" width=\"120px\">"; $rowid = $row['id']; echo "<td valign=\"top\">"; echo "<table> <tr> <td valign=\"top\" class=\"searchtitle\"> ".$row['fname']. ' ' .$row['mname']. ' ' .$row['lname']." </td> </tr>"; ?> and here is where they're set Code: [Select] if (isset($_POST['email'])) { $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); //Query $results = mysql_query("SELECT * FROM users WHERE email = $email AND password = $password"); if(!result) { $_SESSION['error'] = '<span style="color: red">Login Failed. Email or Password is Incorrect <br/>'; } else { $row = mysql_fetch_assoc($results); $_SESSION['userid'] = $row['id']; $_SESSION['email'] = $email; $_SESSION['error'] = 'Login Successful<br/>. Welcome,'. $email; } I am using the following code in PDO query $this->query('SELECT * FROM users WHERE id = :id'); // line 11 $this->bind(':id', $_SESSION['users']['id']); // line 12 it is working on local server, but on live server its giving some error or warning (i am not sure) PHP Notice:  Undefined index: users in ... on line 12 but the query is still working correctly. Please guide me what should i do to stop getting this error or warning or notice. Thanks🙂 i need to create search in database like this select everything from database but it cant be included rows where session id is equal to id of user code Code: [Select] $datum = "$godina-$mjesec-$dan"; $event_select = mysql_query("SELECT * FROM events WHERE event_date='$datum'"); //izlistat evente while ($events = mysql_fetch_array($event_select)) { $id_user = $events['id_user']; $user_select= mysql_query("SELECT * FROM users WHERE id='$id_user' "); $user = mysql_fetch_array($user_select); ... creating table i tried to put something like AND id!=$_SESSION[id] but it didnt work so i need create table for every row where id_user is not equal to session id now it works and i get table for every row do i need if loop or? Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. so i work on wowroster.net making upgrades to roster i have created a user lib for the sit and im now adding sessions but im getten some odd issues.... this is one of the inserts and sent to mysql_query example Code: [Select] UPDATE `roster_sessions` SET `session_user_id` = '0', `session_last_visit` = '1331544818', `session_browser` = '', `session_ip` = '127.0.0.1', `session_time` = '1331545718', `session_page` = 'p=guild-main&a=g:1' WHERE `session_id` = '6m7js82r848kk2s90sjfmuj325' YET.. this is what i get in my database sql dump from my admin Code: [Select] INSERT INTO `roster_sessions` (`sess_id`, `session_id`, `session_user_id`, `session_last_visit`, `session_start`, `session_time`, `session_ip`, `session_browser`, `session_forwarded_for`, `session_page`, `session_viewonline`, `session_autologin`, `session_admin`) VALUES ('5764d5713a7f24c82b30d271460bf68c', '6m7js82r848kk2s90sjfmuj325', '3', 0, 1331544818, 1331545718, '127.0.0.1', '', '', 'addons-main-images-shadow', 0, 0, 0); any clue at all... Hi All! I've written up a script for my website. It\ is basically a virtual job quest. My queries are all correct it just isn't registering the variable for the session. It is $-SESSION[theid']. I want to be bale to use it in my table but I get an error. How do I write this in my SQL query for it to work. The page (when no errors), doesn't show my data. Here is my ocde: Code: [Select] <?php session_start(); include("config536.php"); ?> <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <?php if(!isset($_SESSION['username'])) { echo "<ubar><a href=login.php>Login</a> or <a href=register.php>Register</a></ubar><content><center><font size=6>Error!</font><br><br>You are not Logged In! Please <a href=login.php>Login</a> or <a href=register.php>Register</a> to Continue!</center></content><content><center><font size=6>Messages</font><br><br></center></content>"; } if(isset($_SESSION['username'])) { echo "<nav>$shownavbar</nav><ubar><img src=/images/layout/player.gif><a href=status.php>$showusername</a>.......................<img src=/images/layout/coin.gif> $scredits</ubar><content><center><font size=6>Basic Quests</font><br><br>"; $startjob = $_POST['submit']; $jobq = "SELECT * FROM jobs WHERE username='$showusername'"; $job = mysql_query($jobq); $jobnr = mysql_num_rows($job); if($jobnr == "0") { ?> <form action="<?php echo "$PHP_SELF"; ?>" method="POST"> <input type="submit" name="submit" value="Start Job"></form> <?php } if(isset($startjob)) { $initemidq = "SELECT * FROM items ORDER BY RAND() LIMIT 1"; $initemid = mysql_query($initemidq); while($ir = mysql_fetch_array($initemid)) { $ids = $ir['itemid']; } mysql_query("INSERT INTO jobs (username, item, time, completed) VALUES ('$showusername', '$ids', 'None', 'No')"); $wegq = "SELECT * FROM items WHERE itemid='$ids'"; $weg = mysql_query($wegq); while($wg = mysql_fetch_array($weg)) { $im = $wg['image']; $nm = $wg['name']; $id = $wg['itemid']; } $_SESSION['theid'] = $id; echo "<font color=green>Success! You have started this Job!</font><br><br>Please bring me this item: <b>$nm</b><br><br><img src=/images/items/$im><br><br><br>"; echo $_SESSION['theid']; } if($jobnr == "1") { $finish = $_POST['finish']; $okgq = "SELECT * FROM items WHERE itemid='$yes'"; $ok = mysql_query($okgq); while($ya = mysql_fetch_array($ok)) { $okname = $ya['name']; $okid = $ya['itemid']; $okimage = $ya['image']; } echo "Where is my <b>$okname</b>?<br><br><img src=/images/items/$okimage><br><br><br>"; echo $_SESSION['theid']; ?> <form action="<?php echo "$PHP_SELF"; ?>" method="POST"> <input type="submit" name="finish" value="I have the Item"></form> <?php } } if(isset($finish)) { $cinq = "SELECT * FROM uitems WHERE theitemid='$_SESSION[theid]'"; $cin = mysql_query($cinq); $connr = mysql_num_rows($cin); if($connr != "0") { echo "<font color=green>Success! You have the item.</font>"; } else { echo "<font color=red>Error! You do not have my item!</font>"; } } ?> . I basically just want to know how I can set this session as a variable. Also..I have a user login on every page and I want to be able to destroy JUST THE "theid" session and NOT the username session. How would I do that too? thanks for the help in advance! Hey guys, I'm working a project that requires sessions be stored within the database, as the project I'm working on is on a shared host. But I'm having a problem with getting the data of a session in the database, the other fields like session_id, session_updated, session_created are working fine. I think I've got a bug in my code, but I just can't detect it (frustrating). Database connection class db extends mysqli { private $host; private $user; private $pass; private $db; function __construct( $host='localhost', $user='user', $pass='pass', $db='website' ) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; $this -> db = $db; parent::connect( $host, $user, $pass, $db ); if( mysqli_connect_error( ) ) { die( 'Connection error ('.mysqli_connect_errno( ).'): '.mysqli_connect_error( ) ); } } function __destruct( ) { $this -> close( ); } } Session handler class sessionHandler { private $database; private $dirName; private $sessTable; private $fieldArray; function sessionHandler() { // save directory name of current script $this -> database = new db; $this -> dirName = dirname(__file__); $this -> sessTable = 'sessions'; } function open( $save_path, $session_name ) { return TRUE; } function close() { //close the session. if ( !empty( $this -> fieldarray ) ) { // perform garbage collection $result = $this->gc( ini_get ( 'session.gc_maxlifetime' ) ); return $result; } return TRUE; } function read( $session_id ) { $sql = " SELECT * FROM sessions WHERE session_id=( '$session_id' ) LIMIT 1 "; $result = $this -> database -> query( $sql ); if( $result -> num_rows > 0 ) { $data = $result -> fetch_array( MYSQLI_ASSOC ); $this -> fieldArray = $data; $result -> close(); return $data; } return ""; } function write( $session_id, $session_data ) { //write session data to the database. if ( !empty( $this -> fieldArray ) ) { if ( $this -> fieldArray['session_id'] != $session_id ) { // user is starting a new session with previous data $this -> fieldArray = array(); } } $this -> fieldArray['session_id'] = $session_id; $this -> fieldArray['session_data'] = $session_data; $this -> fieldArray['session_updated'] = time(); $this -> fieldArray['session_created'] = time(); $session_id = $this -> database -> escape_string( $session_id ); $session_data = $this -> database -> escape_string( $session_data ); $session_updated = time(); $session_created = time(); $sql = " INSERT INTO sessions ( session_id, session_data, session_updated, session_created ) VALUES ( '$session_id', '$session_data', '$session_updated', '$session_created' ) "; if( $this -> database -> query( $sql ) !== TRUE ) { return FALSE; } return TRUE; } function destroy( $session_id ) { $sql = " DELETE FROM sessions WHERE session_id=('$session_id') "; if( $this -> database -> query( $sql ) !== TRUE ) { return FALSE; } return TRUE; } function gc( $max_lifetime ) { return TRUE; } function __destruct() { //ensure session data is written out before classes are destroyed //(see http://bugs.php.net/bug.php?id=33772 for details) @session_write_close(); } } The call $session_class = new sessionHandler; session_set_save_handler( array( &$session_class, 'open' ), array( &$session_class, 'close' ), array( &$session_class, 'read' ), array( &$session_class, 'write' ), array( &$session_class, 'destroy' ), array( &$session_class, 'gc' ) ); if( !session_start() ) { exit(); } Any help at all would be appreciated. Kind Regards Mike I want to use session to do a query and will I be able to do this? I have a session that was gathered from login and now i was to use this session to do a query If Yes, How? I need some help with this. A user fills out a form, one of the fields is a zip code field. I need to retrieve that value from MySQL store as a session var and set that value as a variable to use with a weather display API. The ID is being stored from the form page. Here is what I have so far, after the values are submitted into the DB. <?php session_start(); $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}"); while ($row = mysql_fetch_assoc($result)) { $_SESSION['id'] = $row['id']; $_SESSION['zip'] = $row['zip']; } mysql_close($con); ?> and then for the weather API, I need to set the stored variable to something $zip = 'stored zip code value'; Hey guys, Currently Im using: $row = mysql_fetch_array($result) or die(mysql_error()); echo $row['user_family']. " - ". $row['user_registered']; $row['user_family'] = $fam; $_SESSION['family'] = $fam; to take data from a mysql table & set it as SESSION family. However, I cant seem to get this to set. The information IS being taken from mysql because its being echo'd earlier up in the code, but its just not passing to the session. Any ideas? Can someone please explain to me why I cant seem to get my mysql update line to work. I have been trying for a while an still nothing. I am new in php and need some help getting this to work. Please be gentle. a good explaination in newbie talk would be appreciated. The session variable I echoed out does work so I know I am reading the variable in from the other page. thanks <?php session_start(); /* Server side scripting with php CISS 225 Lab # Final Project */ //This section will create variables collected from information sent //by the post method on the createUserProcess. /* $_SESSION['city'] = $_POST['city']; $_SESSION['state'] = $_POST['state']; $_SESSION['zipCode'] = $_POST['zipCode']; $_SESSION['profession'] = $_POST['profession']; $_SESSION['activities'] = $_POST['activities']; $_SESSION['hobbies'] = $_POST['hobbies']; */ $city = $_POST['city']; $state = $_POST['state']; $zipCode = $_POST['zipCode']; $profession = $_POST['profession']; $activities = $_POST['activities']; $hobbies = $_POST['hobbies']; $db = mysql_connect("localhost", "root", ""); mysql_select_db("accountprofile",$db); echo $_SESSION['Email']; //$query = "UPDATE accountprofile SET city = '$city', state = '$state', zipcode = '$zipCode', profession = '$profession', " . " //activities = '$activities', hobbies = '$hobbies' WHERE lastName = 'Hildebrand'"; $query = "UPDATE accountprofile SET city = '$city', state = '$state', zipcode = '$zipCode', profession = '$profession', activities = '$activities', hobbies = '$hobbies' WHERE userName = " .$_SESSION['Email'].""; mysql_query($query,$db); if (mysql_error()) { echo "$query<br />"; echo mysql_error(); } echo "THANK YOU!<br />"; echo "Your profile has been completed!<br />"; ?> Here is my code... Code: [Select] <?php mysql_connect("localhost", "user", "pass")or die("cannot connect"); mysql_select_db("database")or die("cannot select DB"); $myemail = mysql_real_escape_string($_POST['myemail']); $mypassword = mysql_real_escape_string($_POST['mypassword']); $mypassword = md5($mypassword); $myemail = stripslashes($myemail); $mypassword = stripslashes($mypassword); $sql="SELECT * FROM users WHERE email='$myemail' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_start(); $_SESSION["myemail"]= "$myemail"; header("location:home.php"); } else { header("location:fail.php"); } ?> What can I do to this code so that it will also store first name from the database inside a session? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=343257.0 |