PHP - Adding Session Value From Sql
Hi all
I am trying to write a piece of code that takes the value from a form and checks it via an SQL table then adds the session value and the value from the SQL table into the rest of the code as a string. It is for a voucher code in a shopping basket: if(isset($_POST['voucher_code'])) { $vouchercode = $_POST['voucher_code']; $sqlvoucher_code = mysql_query(" SELECT * FROM `voucher_codes` WHERE name = ".$vouchercode.""); $getvoucher_code = mysql_fetch_array($sqlvoucher_code); $_SESSION['voucher_code'] = $_POST['voucher_code']; $voucher_code = $getvoucher_code['value']; header("Location: basket.php"); exit; } Every time I add a value into the form that I know is in the DB it returns a value of 0 even though the value in the DB is 15.95. Please help! Thanks Pete Similar TutorialsHow can i keep adding value to a session??? I need to somehow keep storing more values into an array. session_start(); // store session data $_SESSION['tune_name']=$_GET['tune_name']; $_SESSION['tune']=$_GET['tune']; print_r($_SESSION); So this is what i get from the print_r(); Array ( [attach] => Array ( ) [backups-2] => true [dnb] => true [house] => true [tech-house] => true [uk-garage] => true [uk-grime] => true [uk-hip-hop] => true [uncategorized] => true [warehouse] => true [views] => Music/dnb/Gold Dust (Vocal VIP Mix)_DJ Fresh_192.mp3 [tune_name] => Music/dnb/Dj Ss - We Came To Entertain (Sub Zero Remix).mp3 [tune] => Array ( ) ) ok what i need to do is everytime i click it saves that value above but just appends another value to the array so the session can keep getting larger and larger??? Any help please. I have created a session array on one page and stored some values as $_SESSION['users'] = array( "id" => $row['id'], "fname" => $row['ufname'], "lname" => $row['ulname'] ); and then on another page I have some more values for the same session array "boss" => $row['bossid'], "tasks" => $row['tasks'], "timeframe" => $row['tframe'] I want to add these values into session array both keys and values. is there any way of doing this? Please help Hi: How do I set a password-protected page to time out after 20 minutes or so? I thought it was doing it on the below page, but it is not working. A tutorial I found online. Login.php Code: [Select] <form name="form1" method="post" action="myLogin.php"> <input name="myUserName" type="text" size="40" id="myUserName"> <br /><br /> <input name="myPassword" type="password" size="40" id="myPassword"> </div> <input type="submit" name="Submit" value="Login"> </form> myLogin.php Code: [Select] <?php ob_start(); // Connect to server and select database. //mysql_connect("$host", "$username", "$password")or die("cannot connect"); //mysql_select_db("$db_name")or die("cannot select DB"); // Define $myUserName and $myPassword $myUserName=$_POST['myUserName']; $myPassword=$_POST['myPassword']; // To protect MySQL injection (more detail about MySQL injection) $myUserName = stripslashes($myUserName); $myPassword = stripslashes($myPassword); $myUserName = mysql_real_escape_string($myUserName); $myPassword = mysql_real_escape_string($myPassword); $sql="SELECT * FROM myAdmins WHERE myUserName='$myUserName' and myPassword='$myPassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myUserName and $myPassword, table row must be 1 row if($count==1){ // Register $myUserName, $myPassword and redirect to file "a_Home.php" session_register("myUserName"); session_register("myPassword"); header("location:a_Home.php"); } else { echo " <html> ... </html> "; } ob_end_flush(); ?> myCheckLogin.php (added to each page to see if the person logged-in via Login.php): Code: [Select] <? session_start(); if(!session_is_registered(myUserName)){ header("location:Login.php"); } ?> Any help would be great. Thanks. Hi all I have a php form as follows: <form action="basket.php?action=add&id=1&qty=1" method="post" name="buy-product"> <input name="initial_1" id="initial_1" type="text" size="8" maxlength="1" /> <input name="initial_2" id="initial_2" type="text" size="8" maxlength="1" /> <input name="initial_3" id="initial_3" type="text" size="8" maxlength="1" /> <input name="send" type="submit" class="contact-form-button" id="send" value="Submit" /> Basically I need to add the three initials into a session so that they can be shown in the shopping cart next to the product. How do I add the initials to the session and how do I output them to the shopping cart? At the start of my basket.php script I have: $cart = $_SESSION['cart']; $action = $_GET['action']; $id = $_GET['id']; $qty = $_GET['qty']; $initial_1 = $_POST['initial_1']; $initial_2 = $_POST['initial_2']; $initial_3 = $_POST['initial_3']; I now need to create a table with the cart showing item, price and initials. Cheers Pete. hello all, I was hoping someone could help me figure out how to add sizes to my shopping cart. Right now the items add just fine. The site sells shirts and I'm having trouble displaying the sizes once selected and added to the cart. It will post the size selected, but if the customer tries to add another shirt the size will overwrite the last. Any help is appreciated. Heres how I add items to the cart... Code: [Select] session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'empty': if($cart) { unset($cart); } break; case 'add': if ($cart) { $cart .= ','.$_GET['product_id']; } else { $cart = $_GET['product_id']; } break; The form with the size selection and add to cart button.. Code: [Select] <form action="cart.php?action=add&product_id=<?php echo $row_rs_products['product_id'] ?>" method="POST" name="addcart" id="addcart"> <table width="300" border="0"> <tr> <td><label for="sizes"></label> <select name="product_size" id="product_size" title="<?php echo $row_rs_products['product_size']; ?>"> <?php do { ?> <?php } while ($row_rs_sizes = mysql_fetch_assoc($rs_sizes)); $rows = mysql_num_rows($rs_sizes); if($rows > 0) { mysql_data_seek($rs_sizes, 0); $row_rs_sizes = mysql_fetch_assoc($rs_sizes); } ?> </select></td> <td><input type="submit" name="submit" id="submit" value="add to cart"> function displaying the cart.. Code: [Select] function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; // start div $output[] = '<div id="cart_table">'; // $output[] = '<tr>'; $output[] = '<td><h4>Product</h4></td>'; $output[] = '<td><h4>Item No.</h4></td>'; $output[] = '<td><h4>Price</h4></td>'; $output[] = '<td><h4>Size</h4></td>'; $output[] = '<td><h4>Quantity</h4></td>'; $output[] = '<td><h4>Price Total</h4></td>'; $output[] = '<td><h4> </h4></td>'; $output[] = '</tr>'; //new row foreach ($contents as $product_id=>$qty) { $sql = 'SELECT * FROM products WHERE product_id = '.$product_id; $result = $db->query($sql); $row = $result->fetch(); extract($row); // $output[] = '<tr>'; $output[] = '<td><a href="product.php?product_id='.$product_id.'">'.$product_title.'</a></td>'; $output[] = '<td>'.$product_plu.'</td>'; $output[] = '<td>$'.$product_price.'</td>'; // //$output[] = '<td>'.$product_size.'</td>'; $output[] = '<td>'.$_POST['product_size'].'</td>'; // $output[] = '<td><input type="text" name="qty'.$product_id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>X $'.($product_price * $qty).'</td>'; $total += $product_price * $qty; $output[] = '<td><a href="cart.php?action=delete&product_id='.$product_id.'" class="r">Remove</a> </td>'; $output[] = '</tr>'; //end div $output[] = '</div>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>'; $output[] = '<div class="float-right"><button type="submit">Update cart</button>'; $output[] = '</form>'; I am a little experienced with PHP sessions, but not totally as I haven't got my head completely around its logic yet, as your about to see. I wonder wondering how I can go about adding a session entity from a HTML form input? I'm guessing it will be something like: $_POST['name'] => $_SESSION['delivery']['name']; Then, to echo the session entity, you would simply do something like: echo $_SESSION['delivery']['name']; ? 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 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! 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> 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. 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. 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. I am trying to get sessions to work right Here are my settings: session.gc_maxlifetime = 60 session.gc_probability = 1 session.gc_divisor = 1 session.cookie_lifetime = 0 (when browser closes) So say I have two php files: php1.php session_start(); $_SESSION['var1'] = 'var1'; php2.php session_start(); echo $_SESSION['var1']. '<br>'; So if I go to php1 it will set the variable and then I can go to php2 and it will echo the variable. This works. But if I don't do anything and then go back to php2 after 60 seconds the variable should no longer exist. This part is not working. What do I need to change to get it to work? Hi People, I am on a deadline and finding that my code does not work in php5 and I have to change it to work. Just wonder if anyone can spot the obvious within my code. This all worked in php4 but now I have to rewrite it. Basically its a little order system. <? include("inc/connect.php"); // Continue start session. // We need to first check to see if an item with the SID and cat and product_code exists in the database, // if it does then we need to update that item, if not then we need to add the item // clean out any malicious data foreach ($_REQUEST as $k => $v) { $_REQUEST[$k] = (get_magic_quotes_gpc() ? strip_tags($v) : strip_tags(addslashes($v))); } session_start(); { $sql = "SELECT * FROM orders WHERE sid = '$PHPSESSID' AND product_id = '$product_id' "; $sql_result = mysql_query($sql); if (mysql_num_rows($sql_result) ==0) { # setup SQL statement $SQL = " INSERT INTO orders (sid,product_id,product_title,qty,standard_price,deluxe_price) VALUES ('$PHPSESSID','$product_id','$product_title','$qty','$standard_price','$deluxe_price')"; #execute SQL statement $result = mysql_db_query( azflowers,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } } else { # setup SQL statement $SQL = " UPDATE orders SET qty = qty +1 WHERE sid = '$PHPSESSID' AND product_id = '$product_id' "; #execute SQL statement $result = mysql_db_query( azflowers,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } } header("Location: http://www.site.com/site/cart.php?sid=$PHPSESSID"); exit; } ?> Hi, I am trying to get the value of a session veriable and if the variable contains a certain word it will show an error message, else just continue as normal. if (isset($_POST['selectroom'])) {$_SESSION['room'] = $_POST['selectroom'];} if (!isset($_SESSION['room'])) $room = "RoomNameA"; else $room = $_SESSION['room']; Please Advise, - Stuart This is weird. I thought session_destroy erased your session id: echo "session is ".session_id(); session_destroy(); echo "<br>session now is ".session_id(); When I run it i get: Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is But when I reload the page I get the same thing! Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is If session_id was destroyed (it echoed blank to prove this) why does it get repopultaed with the same session id when I reload the browser? I'm trying to make my own shopping cart for the first time and having a problem getting products to add to it. All I get is "No product in cart.". Its nothing special now, I'm just trying to reach the first stepping stone of adding something successfully to the session. index.html Code: [Select] <?php session_start(); ?> <?php $cart = $_SESSION['cart']; if (!$cart) { echo "No product in cart."; } if ($cart) { foreach ($id) { echo $id; } } ?> <A href="index.html?action=add&id=1">Add to cart</A> What have I done wrong and what am I suppose to do? How to add more data into $_SESSION? I have following code: Code: [Select] if(isset($_GET['poredi']) && $_GET['poredi'] == "upo"){ $idp = intval($_POST['idp']); $sql = "SELECT * FROM product WHERE product_id={$idp}"; $query=mysql_query($sql); if(mysql_num_rows($query)!=0){ $row=mysql_fetch_array($query); $_SESSION['poredi'] = $row['product_id']; } } On click it need to store more product_id, and after that i have to be able to do query with data (find all data with product_id)? People please help me i beg you, been trying to do this same thing for the past 4hours (-) close to giving up on php and learning a new languages :S Well as I was updating my login/sign up because its old and it was not very safe. Now my session are not working, well they work when i set them but it wont destroy so you cant log out. I have tryed doing 100 ways but i get one error or another or it dont work out all. login page <?php session_start(); require_once "../config.php"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Admin CP</title> <?php $flag=0; if(isset($_POST['Submit'])) { $con = database_connect(); $username = $_POST['username']; $password = $_POST['password']; clean($username); clean($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); mysql_close($con); $md5password= md5($password); database_connect(); $sql="select * from $membertables WHERE username='$username' and password='$md5password' and (userlevel='1' or userlevel='2') "; $res=mysql_query($sql); if(!$res) { die('error in database'); } $row=mysql_fetch_array($res); if(mysql_num_rows($res)>0) { $_SESSION['logged_in'] ="loggedin"; $_SESSION['userid']=$row['uid']; $_SESSION['username']=$row['username']; $_SESSION['userlevel']=$row['userlevel']; session_write_close(); header('location:welcome.php'); } else { $_SESSION['logged_in'] = "notloggedin"; $flag=1; } } ?> <script language="javascript"> function valid() { if(document.frm1.txtuname.value=="") { alert('Enter User-ID'); document.frm1.txtuname.focus(); return false; } if(document.frm1.txtpass.value=="") { alert('Enter Password'); document.frm1.txtpass.focus(); return false; } } </script> <!-- CSS --> <link href="style/css/transdmin.css" rel="stylesheet" type="text/css" media="screen" /> <!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="style/css/ie6.css" /><![endif]--> <!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="style/css/ie7.css" /><![endif]--> <!-- JavaScripts--> <script type="text/javascript" src="style/js/jquery.js"></script> <script type="text/javascript" src="style/js/jNice.js"></script> </head> <body> <div id="wrapper"> <!-- h1 tag stays for the logo, you can use the a tag for linking the index page --> <h1><a href="#"><span>Transdmin Light</span></a></h1> <!-- You can name the links with lowercase, they will be transformed to uppercase by CSS, we prefered to name them with uppercase to have the same effect with disabled stylesheet --> <ul id="mainNav"> <li></li> <!-- Use the "active" class for the active menu item --> <li></li> <li></li> <li class="logout"></li> </ul> <!-- // #end mainNav --> <div id="containerHolder"> <div id="container"><!-- // #sidebar --> <!-- h2 stays for breadcrumbs --> <h2>Login »</h2> <div id="main"> <form action="index.php" method="post" name="frm1" id="frm1" onSubmit="return valid();"> <table width="100%" border="0" cellpadding="0" cellspacing="0""> <tr> <td align="left"><table border="0" cellpadding="5" cellspacing="1" width="576"> <tbody> <tr> <td colspan="2" align="center"><br /> Please enter your User Name and password below.<br /></td> </tr> <?php if($flag==1) { ?> <tr> <td width="333" align="center" style="background-color: #F00; text-decoration: underline; color: #FF0;" ><p>Enter Valid User-Name or Password </p></td> </tr> <?php } ?> <tr> <td align="right" >User Name:</td> <td width="344"><input style="background-color: rgb(221, 234, 248);" class="form_text" id="username" name="username" /> <script language="JavaScript" type="text/javascript">document.getElementById('txtuname').focus(); </script></td> </tr> <tr> <td align="right">Password:</td> <td><input class="form_text" id="password" name="password" type="password" /></td> </tr> <tr> <td> </td> <td> <input class="buttons" value="sign me in" name="Submit" type="submit" id="Submit" /> </td> </tr> <tr> <td style="height: 30px;"> </td> <td> </td> </tr> </table> </td> </tr> </tbody> </table> </form> </div> <!-- // #main --> <div class="clear"></div> </div> <!-- // #container --> </div> <!-- // #containerHolder --> <p id="footer"><?php echo $footer ?></p> </div> <!-- // #wrapper --> </body> </html> <?php session_start(); if($_SESSION['logged_in']="loggedin"); else{ header('location:index.php'); } ?> sign out page <?php session_start(); session_unset(); session_destroy(); header('location:index.php'); ?> |