PHP - Session Array Issue
Hi All,
I'm running trying to add key and values to an array on multiple pages, but it seems to override the array each time I add variables on the next page, even though the keys are different. Each page has something like this: Code: [Select] <label class="yes"><input type="radio" name="form_field[<?php echo "number".$f1; ?>]" value="0" > Yes</label> <label class="no"><input type="radio" checked="checked" name="form_field[<?php echo "number".$f1; ?>]" value="1" > No</label> <label class="unsure"><input type="radio" name="form_field[<?php echo "number".$f1; ?>]" value="2" > Unsure</label> I then collect it as well as other page variables with: Code: [Select] session_start(); foreach($_POST as $name => $value) { $_SESSION[$name] = $value; } on all following pages. But rather than adding to the array it writes over it each time. Any ideas on what's going wrong here. Should the array simply be able to continue to collect the keys or do I need to do something else? Thanks. Similar TutorialsHello all, I have an error handler that I need to append messages to (First name not right, Last name not right, etc) I'm using a session array to handle all error messages titled GORB. How come this code won't work? $_SESSION['GORB']['message'][] = "First name wrong"; $_SESSION['GORB']['message'][] = "Last name wrong"; How can I get it to work? I already have the handler output written and functioning fine, I just need to get it to loop over an array of errors instead of just one. I'm using the PHPmotion script, with a use-a-credit to view-a-video mod. When the user logs out, the viewed video should not be available again to view, until he logs back in and chooses it chooses it, via a credit, but it is still available when he logs back in. Any ideas on what file may be responsible for what I guess you could call 'clearing the session'? Hi Everyone I have a weird session issue going on and i'm not sure what is causing it. Basically any sessions that i set are randomly expiring sooner than they should be. As a test I did the following: Code: [Select] <?php session_start(); if(isset($_SESSION['views'])){ $_SESSION['views'] = $_SESSION['views']+ 1; }else{ $_SESSION['views'] = 1; } echo "views = ". $_SESSION['views']; echo '<p><a href="testpage.php">Refresh</a></p>'; ?> If i continue to click the refresh button, i sometimes get to 30 and then it starts at 1 again. Other times ill get to 20 and then back to 1. It has also sometimes skips a couple of counts from 7 to 11 as an example in one click. Any one come across this before? I have been reading up online and some have mentioned PHP upgrades from php4 to php5 cause some issues and specifically the hosting company changing the session.save_path. If this was the case, it wouldn't even count to 10, would it? Any help would be really appreciated. thanks in advance About to pull my hair out. Looks simple, I think it's simple, but something is not behaving. I have a simple login page (loginpage.php) which checks a database for the FamilyID and Password, if it is a match, then it redirects them to userspage.php. I eventually want to use the FamilyID as a filter for my database so I only show the stuff relative to that FamilyID. Using CS5 and the built in functions, and it looks to me that the session variable 'MM_Username' should contain the FamilyID which is "adminid" in my database. It appears to work since it sends me to my userspage.php when I enter a valid FamilyID and Password, but it will not show me my session variable on the that page!!! PLEASE PLEASE HELP...Slap me in the face if it's a stupid question, but I have spent WAY too much time trying to figure what is wrong. I have included my code: CODE FOR LOGINPAGE.PHP <?php require_once('Connections/MyTest.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['familyid'])) { $loginUsername=$_POST['familyid']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "userspage.php"; $MM_redirectLoginFailed = "loginpage.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_MyTest, $MyTest); $LoginRS__query=sprintf("SELECT adminid, password FROM `admin` WHERE adminid=%s AND password=%s", GetSQLValueString($loginUsername, "int"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $MyTest) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?> <!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>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="POST" action="<?php echo $loginFormAction; ?>"> <p> <label for="familyid">FamilyID:</label> <input type="text" name="familyid" id="familyid" /> </p> <p> <label for="password">Password:</label> <input type="text" name="password" id="password" /> </p> <p> <input type="submit" name="Submit" id="Submit" value="Submit" /> </p> </form> </body> </html> CODE FOR USERSPAGE.PHP <?php if (!isset($_SESSION)) { session_start(); } ?> <!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>Untitled Document</title> </head> <body> <strong>YOU MADE IT! </strong> <?php echo $_SESSION['MM_Username']; ?> </body> </html> THANKS IN ADVANCED!!! I have 500 users using software I have developed, and 495 do not have a timeout problem. Our default is to timeout after 60 minutes, but one particular office times out randomly and without warning. The normal procedure is, like online banking, a pop up comes up to let them know they will be logged out in 60 seconds, or they can click continue to stay logged in.
The timer is based on JS, but on each page load a PHP function checks to see if they are timed out, and if they are, redirect them to the login page. The JS pop up never occurs, so obviously the countdown hasn't happened, but when they click on a link, they are redirected to the login page.
Since the issue only occurs in one office, it leads me to believe it is a firewall or anti-virus issue, but I'm not sure...
Anyone have any thoughts on this?
I was told that using a Session will allow me to capture an Object and pass it between pages. I tried following what I read online and what someone sugegsted but it is not working. This is the error I get when running my test application... Quote Catchable fatal error: Argument 1 passed to Microwave::receiveItem() must be an instance of Bowl, instance of __PHP_Incomplete_Class given, called in /Users/user1/Documents/DEV/++htdocs/Soup/cook.php on line 13 and defined in /Users/user1/Documents/DEV/++htdocs/Soup/classes/Soup.class.php on line 31 Call Stack # Time Memory Function Location 1 0.0095 56412 {main}( ) ../cook.php:0 2 0.0101 68272 Microwave->receiveItem( ) ../cook.php:13 I would really appreciate it if someone could look at my code and see where the problem is at. My guess is that it is in cook.php, but who knows?! Attached is a ZIP of my entire directory structure. Thanks, TomTees I'm having an issue with sessions and session_set_save_handler. Note: new at OO PHP I'm using an MVC written mostly from a tutorial and it all seems to be working, except for sessions. I've got session_set_save_handler as a class SessionHandler. If I include it into the main index page and create an instance, I get an error 'Undefined variable: _SESSION' for my index view file. If I instead include a global.php file into the main index page and include the session class into the global.php page, and create an instance, the error goes away and session_set_save_handler saves the session variables into my database. (1)On my index page for debugging I've got a var_dump of $_SESSION to see which session variables are set. On my login page I've got a form token that is saved to a session variable. When I go to the login page that session token variable is set and doing a var_dump on the page shows it is indeed being set, however, when I click back to the main index page, the index var_dump(1) shows the session variable is no longer set. But then if I login it correctly redirects me to a user logged in page and echos the username of the user logged in correctly, but still does not show the form token session variable in the var_dump for index(1). But then if I navigate to the login form page where the form token should be initially set, it now sets it correctly and going to the index page indeed shows the token set. form token being set on login view page: Code: [Select] $login_token = $_SESSION['login_token'] = md5(uniqid(mt_rand(),true)); var_dump on index page before login (even if I navigate to login page then back to index it remains blank when it should instead show the form token session variable) Code: [Select] array empty var_dump on index page after login. Code: [Select] array 'lu_user' => string 'admin' (length=5) 'lu_user_id' => string '6' (length=1) 'user_sess_time' => int 1326544148 var_dump on index page after login, navigating to login form page (where login_token is set), then navigating back to index: Code: [Select] array 'lu_user' => string 'admin' (length=5) 'lu_user_id' => string '6' (length=1) 'user_sess_time' => int 1326544148 'login_token' => string 'c260e76dd65f0d9b6e881cfc9a4b33e1' (length=32) Magically the login_token now shows, but only after logging in and setting the other variables. It seems it's not saving the login_token when it's initially set, but only after logging in which it shouldn't be doing. The same issue arises with any other session variables that I set elsewhere (only displayed after user login). If I remove session_set_handler the sessions set correctly but naturally the data is no longer added to the database. If I do var_dump(get_included_files()); it shows the session class is correctly being included. I was thinking it's an issue with session_start() but if I add that in or try to create another instance of the session class on the other pages, I get an error stating they've already been called and cannot be called again. So then they must be getting called, right? So now I'm thoroughly confused. More code below, sorry for the long post. Hopefully I've provided all necessary information. Index includes global.php, which contains: Code: [Select] require 'framework/SessionHandler.php'; $sess = new SessionHandler(); And the session handler class is (Database class is included into index which is why you cannot see it instantiated here): Code: [Select] <?php class SessionHandler { function __construct() { session_set_save_handler ( array(&$this, 'open'), array(&$this, 'close'), array(&$this, 'read'), array(&$this, 'write'), array(&$this, 'destroy'), array(&$this, 'gc') ); session_start(); ini_set('session.gc-maxlifetime', 1800); if (isset($_SESSION['lu_user'])) { if (!isset($_SESSION['user_sess_time'])) { $_SESSION['user_sess_time'] = time(); } elseif (time() - $_SESSION['user_sess_time'] > 1800) // 30 mins { session_regenerate_id(TRUE); $_SESSION['user_sess_time'] = time(); } } } function open() { $this->db = new Database(); } function close() { return $this->db = null; } function read($id) { $stmt = $this->db->prepare('SELECT * FROM sessions WHERE id = :id'); $stmt->execute(array(':id' => $id)); if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { return $data = $row['data']; } else { return ''; } } function write($id, $data) { $access = time(); if (isset($_SESSION['lu_user'])) { $session_id = session_id(); $username = $_SESSION['lu_user']; $stmt = $this->db->prepare('REPLACE INTO sessions (id, access, data) VALUES (:id, :access, :data)'); $stmt->execute(array(':id' => $id, ':access' => $access, ':data' => $data)); } } function destroy($id) { if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); } $stmt = $this->db->prepare('DELETE FROM sessions WHERE id = :id'); $stmt->execute(array(':id' => $id)); } function gc($max) { $old = time() - $max; $stmt = $this->db->prepare('DELETE FROM sessions WHERE access < :old'); $stmt->execute(array(':old' => $old)); } function __destruct() { session_write_close(); } } Hi guys i've spent 3 whole days trying to get this to work but it dosent. My issue is very similar almost the same as: http://www.phpfreaks.com/forums/index.php?topic=296100.15 but with the code i have. Basically i have custom member pages. member1.php member2.php the design and content will be custom to each member, they also have their own login page. Each member should be able to access their page and simply view their secure area. They should not be able to log into another users area if they dont have the username or password for it. Now the problem is, i have this entire script setup and it works, however i fear there is something wrong with the sessions which allows other members to access other members pages with their own passwords and usernames because they share the same database. So the script executes thinking its a valid user and lets them in. Here is my login checker once the user is validated they are sent to their own folder header("Location: ../{$loginusername}/index.php"); and are able to view the page. Code: [Select] <?php require_once('../config.php'); // Connect to the server and select the database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db")or die("Unable to select database"); // The username and password sent from login.php $loginusername=$_POST['username']; $loginpassword=$_POST['password']; //The following bit of coding protects from MySQL injection attacks $loginusername = stripslashes($loginusername); $loginpassword = stripslashes($loginpassword); $loginusername = mysql_real_escape_string($loginusername); $loginpassword = mysql_real_escape_string($loginpassword); $sql="SELECT * FROM $tbl WHERE username='$loginusername' and password='$loginpassword'"; $result=mysql_query($sql); // Count how many results were pulled from the table $count=mysql_num_rows($result); // If the result equals 1, continue if($count==1){ session_start(); $_SESSION["loginusername"] = $loginusername; $_SESSION['user1'] = $username; // store session data //echo "User: = ". $_SESSION['loginusername']; //retrieve data header("Location: ../{$loginusername}/index.php"); } // If not successful, inform the user of error else { echo "Wrong Username or Password"; } ?> Now here is the secure page sample: Code: [Select] <?php session_start(); if (!$_SESSION['user1']){ header("Location: login.php"); }else{ print "its working!"; } ?> <html> <body> Login Successful for </body> </html> For each login page i have given each user it's own session.. this works, however if user1 logs in and simply changes the url to user2 and enters his user2 password he is granted access giving him new sessions which means he has access to everything. Im pretty sure im missing something really small any help would be appreciated. I have a website uploaded onto Host Gator hosting and the sessions are carried over to the other pages ok. When using the same website in XAMPP it does not carry over the session to the next page and need to login again. If i log in it puts the following after the URL - ?sid=3b71942d410d84c45f9f4433561c325a The when i go to another link it loses the sid and i'll need to manualy past it into the next URL to get it working unless i log in again on the new page. This is only happening with XAMPP but working fine in the Host Gator hosting environment. Please help! My login is integrated with the phpbb3 login. This is the code at the beginning of every page - Code: [Select] <?php ob_start(); define('IN_PHPBB', true); $phpbb_root_path = './phpbb3/'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); ?> I am createing a simply quiz site, where in order to participate in the quiz, you must first be logged in. While working on my local machine, the code works perfectly. I use the followin to create a session ID; $_SESSION['SESS_ID'] = $member['id']; Then, on my main page where i want dynamic code i include the following; if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID']) == '')) { print (" <div style='float:left; width:400px; height:215px; margin-left:500px;'> <form class='login' method='post' action='login-form.php' style='float:right; margin-top:120px;' > <input type='submit' class='button' name='submit' value='Sign In' style='float:right ; margin-right:20px;'> </form> <p style=' margin-top:170px; margin-left:160px;'>New Member? Start <a href='register-form.php'>Here</a></p> </div> " ); } else { print "<h4 style='float:right; text-align: right; margin-top:150px; margin-right:50px;'>Welcome ". $_SESSION['SESS_NAME']. " <a href='logout.php' style='float:right; text-align:right;'>Sign Out</a></h4> "; For some reason, when the site is on the server, the session ID does not seam to get passed along. Any Ideas how to remediy this? the website is kingdomquiz.com if anybody is interested. I am having a very strange issue on one server. I have the same code in a development server running fine, but in my prod server it is failing. Here is the main issue: I have a user authentication routine that accepts UserID and Password from a form and validates it against a MySQL database. So to start, UserId and Password are entered via POST variables as is standard: $UserId=@$_POST['UserId']; $Password=@$_POST['Password']; The Password is encrypted using a standard crypt method such as: $encrypt = crypt($Password,'6!68$7435!'); And this is stored in a MySQL database. This part is working fine, that is, the password is encrypted in value and stored in the MySQL database as 'epasswd'. On login, I am using session, so a standard session_start() and eventual session_destroy() on logout are used. The reason I mention this is because I suspect my issue is session related. So normally this works well. User logs in and I check credentials as follows in one part of my auth routine: elseif(UserAuth($UserId,$Password)){ $UserLogin=$UserId; session_start(); $_SESSION['UserLogin'] = $UserLogin; sql_insertActivity(); header("Location: home.php"); And the auth routine is as follows: <? function UserAuth($UserId,$Password){ global $conn; $Stmt="select epasswd from Users where UserId='$UserId' and Approved='1' or Approved='-1' or Approved='-2'"; $Result = mysql_query($Stmt, $conn) or die(mysql_error()); $Result=mysql_fetch_row($Result); $epasswd=$Result[0]; $retval=($epasswd==crypt($Password,$epasswd)); return($retval); } ?> So I am checking for a valid UserID and Password on form input, and I have a few other variables set for approved status. The retval checks the password they enter versus the encrypted value for a match. This usually works well. Then login occurs and session started, etc. Here is the issue. I added a quick admin routine a little while ago which helps reset a user's password to a temporary value. Once this value is set, along with a setting of approved=-1 in my database, then the user is re-directed to a Change Password screen to update his or her password. *Note: I changed the value to 'Charlie' for this discussion purpose. Here is that quick admin routine I run when I need to change a User to a temp setting: // ----- Establish database connection ----- require "../inc_php/inc_mysql_prod.php"; // $UserId=@$_GET['UserId']; $Password='Charlie'; $encrypt = crypt($Password,'6!68$7435!'); $sql = "UPDATE Users set epasswd='$encrypt', approved='-1' where UserId='$UserId'"; mysql_query($sql, $conn) or die(mysql_error()); So this does work as I validate the UserID is updated in the MySQL database along with an encrypted value for 'Charlie'. However, this is where things breakdown going forward. When the user logs in with the temp credentials, and enters in the Change password routine, their new password is saved in the table. However, when logging back in with the new credentials, the new password is not valid. And what's odd is that 'Charlie', the temp password, works for them on login and nothing else, no matter how many times they change the password in the form. So seems a case of session management out of control? What is the issue? I am defining session on all Php pages used, and have a logout to destroy session, etc. The temp password routine is something I run as an admin in the system and it doesn't have a session start statement. And I am not defining any global vars for Password. I lloked into session management and tried some UNSET paths and such, but may not be doing this correctly. Also I did a complete stop apache, remove all php sess_ files, restart and to no avail. I tried the clear my client side cookies deal in the browser, and still the same problem. What is odd is that this same set of code works fine on my other server, but breaks down on the mirrored server. They are essentially twins in all setup. Some minor differences between the two servers regarding PHP setup that might(?) make a difference. DEV server: SERVER_SOFTWARE Apache/2.2.3 (Red Hat) PROD server: (server showing the issues): SERVER_SOFTWARE Apache/2.2.3 (CentOS) HTTP_COOKIE PHPSESSID=3gocr0hhelvsjjlt63pp4qlnp3 _REQUEST["PHPSESSID"] 3gocr0hhelvsjjlt63pp4qlnp3 _COOKIE["PHPSESSID"] 3gocr0hhelvsjjlt63pp4qlnp3 _SERVER["HTTP_COOKIE"] PHPSESSID=3gocr0hhelvsjjlt63pp4qlnp3 Thanks appreciate the help! -Eddie why is it that i have to click add to cart 2 time inorder for the eventname and eventinfo to show up if i click one time it add to the cart but it shows nothing Code: [Select] <?php //if user attempts to add something to the cart if (isset($_POST['tid'])) { $tid = $_POST['tid']; $howmany = $_POST['howMany']; $wasFound = false; $i = 0; // If the cart session variable is not set or cart array is empty if (!isset($_SESSION["cart"]) || count($_SESSION["cart"]) < 1) { // RUN IF THE CART IS EMPTY OR NOT SET $_SESSION["cart"] = array(1 => array("item_id" => $pid, "quantity" => $howmany)); } else { // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT foreach ($_SESSION["cart"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $tid) { //there will recive a message $msg = "Item is already in the cart"; $wasFound = true; } // close if condition } // close while loop } // close foreach loop if ($wasFound == false) { array_push($_SESSION["cart"], array("item_id" => $tid, "quantity" => $howmany)); } } header("location: cart.php"); exit(); } ?> <?php //render the cart for the user to view on the page $cartOutput = ""; $cartTotal = ""; $product_id_array = ''; if (!isset($_SESSION["cart"]) || count($_SESSION["cart"]) < 1) { $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>"; } else { // Start the For Each loop $i = 0; foreach ($_SESSION["cart"] as $each_item) { $item_id = $each_item['item_id']; $sql = mysql_query("SELECT * FROM events WHERE id='$item_id' LIMIT 1"); while ($row = mysql_fetch_array($sql)) { $eventname = $row["eventname"]; $eventinfo = $row["eventinfo"]; $studentsprice = $row["studentsprice"]; } //adding the price of the tickets //getting the total $totalprice = $studentsprice * $howmany; setlocale(LC_MONETARY, "en_US"); //this will amke it so it looks like real money $totalprice = money_format("%10.2n", $totalprice ); $cartOutput = ""; //this is the table the will replace the table row below //this is in order $cartOutput.= "<tr>"; $cartOutput .= "<td>".$eventname."</td>"; $cartOutput .= "<td>".$eventinfo."</td>"; $cartOutput .= "<td>".$studentsprice."</td>"; $cartOutput .= "<td>".$howmany."</td>"; $cartOutput .= "<td>".$totalprice."</td>"; $cartOutput .= "<td>".X."</td>"; $cartOutput .= "</tr>"; } } ?> how do i set a session array? e.g. set session with variable $value = 13. then set the next $value = 15 . = 13 and [1]=15 how do i set this session. up? so it keeps on updating the array This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=344127.0 Hello everyone and thanks in advance for the help. I am working on a permission system for a site I am creating that will be used to restrict access to various areas of the site. I have a table with all the permission that is linked to a group that the user is a member of. I then use a query to get a list of the permission ids the user is part of and put those into the session array. I used a basic login script I found online I planned on modifying to add my own features and to make more secure. Originally it had just a member id and member name variable in the session array saved in the login script which are both working fine after login. I am using a dynamic variable to set one session variable for each permission with the id being the changing part in the variable name. The problem I found is that the new variables are not being set. When i removed the redirect from my login script so I could check the problem I found that the temp variable, which is also set before it saves to the session array, is blank as well. If I hit refresh on my browser the new variables become set and all is well. I was talking to nvee in irc chat who said I need to make a function on the page I am redirected to that checks if the variable exists. I looked through the original code of the login script I am using and found that this seems to be how they did it as well so I added an if statement to my index page to check if the variable has a value with and without using if isset. In both cases the new variable is still not getting set. He also gave me some pointers to help make my login checks more secure but the main thing IM concerned with right now is to make my new permission variables accessible to the session. My login script is available in my pastebin. Hi Guys, I am having a small problem with an array. I want to push information from a form into an array. However each time I do it it just replaces the last entry in the array with the information in stead of adding a new value to the array. Code: [Select] <?php // if generate is pressed if(isset($_POST['generate'])){ // get values from form $name = htmlspecialchars($_REQUEST['add']); array_push($stack, $name); print_r($stack); } ?> Can anybody help? Thanks Ed Hello Everybody,
i have shopping-cart with session_product.
i add arrays per button to the session.
i want get the shipping1 and shipping2 fields from the array where the field qty great is or equal to 2 >= 2.
i did this manualy in my example to get shi1 and shi2 lines 15 and 16.
how can i get shipping1 and shipping2 automaticly?
thank you very much for your help.
here is my code
01.<?php 02.$maxshipping1=0; 03.foreach ($_SESSION['products'] as $pro1) { 04.$maxshipping1 = max($maxshipping1, $pro1['shipping1']); } 05.?> 06.<?php 07.$maxshipping2=0; 08.foreach ($_SESSION['products'] as $pro2) { 09.$maxshipping2 = max($maxshipping2, $pro2['shipping2']); } 10.?> 11.<?php 12.$maxqty=0; 13.foreach ($_SESSION['products'] as $quant) { 14.$maxqty = max($maxqty, $quant['qty']); } 15.$shi1 = $_SESSION["products"][0]["shipping1"]; 16.$shi2 = $_SESSION["products"][0]["shipping2"]; 17.?>the Arrays looks like the following: Array ( [0] => Array ( [product] => Orangensaft 0,3l [code] => 5 [qty] => 3 [price] => 2.99 [shipping1] => 5 [shipping2] => 7 ) [1] => Array ( [product] => Kuchen [code] => 3 [qty] => 1 [price] => 2.95 [shipping1] => 4 [shipping2] => 6 ) [2] => Array ( [product] => Burger 200g [code] => 4 [qty] => 1 [price] => 3.95 [shipping1] => 1 [shipping2] => 3 ) [3] => Array ( [product] => Pizza Pollo [code] => 2 [qty] => 1 [price] => 5.95 [shipping1] => 2 [shipping2] => 4 ) [4] => Array ( [product] => Sake Maki Lachs, 6 St�cke Pommes [code] => 4236134485469 [qty] => 1 [price] => 2 [shipping1] => 1 [shipping2] => 2 ) ) I am trying to send some arrays to another page using sessions. The first array I send works fine when I simply print the array on the next page but the second and third arrays are not being created. Code Code: [Select] <?php require("dbconn.php"); $query = mysql_query("SELECT username, idcustomers FROM customers WHERE username='$customeruser' "); if (!$query) { die('Invalid query: ' . mysql_error());} $row = mysql_fetch_assoc($query); echo $row['username']; $id=$row['idcustomers']; echo $id; $productquery = mysql_query("SELECT productid, price1, price2, price3, price1_type, price2_type, price3_type, prod_name, price_det FROM product_pricing WHERE idcustomers='" . mysql_real_escape_string($id) . "' ORDER BY productid"); if (!$productquery) { die('Invalid query: ' . mysql_error());} $counter = 1; $itemcode_array = array(); while ($row = mysql_fetch_assoc($productquery)) { ?> <tr class="ordertable"> <td class="table_item" name="itemcode<?php echo $counter;?>"><?php echo $row['productid']; ?></td><?php $itemcode_send = $row['productid']; array_push($itemcode_array, $itemcode_send); ?> <td class="table_name" name="prodname<?php echo $counter;?>"><?php echo $row['prod_name']; ?></td><?php $prod_name_send = $row['prod_name']; array_push($prodname_array, $prod_name_send); ?> <td class="table_pdet" name="prod_det<?php echo $counter;?>"><?php echo $row['price_det']; ?></td><?php $price_det_send = $row['price_det']; array_push($pricedet_array, $price_det_send); ?> <td class="table_price" name="price1<?php echo $counter;?>"><?php echo $row['price1_type']; ?> $<?php echo $row['price1']; ?></td> <td class="table_quant" name="quant1"><input type="text" name="quant1<?php echo $counter;?>" size="4" /></td> <td class="table_price" name="price2<?php echo $counter;?>"><?php echo $row['price2_type']; ?> $<?php echo $row['price2']; ?></td> <td class="table_quant" name="quant2"><input type="text" name="quant2<?php echo $counter;?>" size="4" /></td> <td class="table_price" name="price3<?php echo $counter;?>"><?php echo $row['price3_type']; ?> $<?php echo $row['price3']; ?></td> <td class="table_quant" name="quant3"><input type="text" name="quant2<?php echo $counter;?>" size="4" /></td> <td class="table_note" name="notes"><input type="text" name="note<?php echo $counter;?>" size="28" /></td> </tr> <?php ($counter++); } ?> <?php mysql_close($dbConn); ?> </table> <p><input type="submit" name="submit" value="Confirm" /> <input type="reset" /></p> </form> <?php print_r($prodname_array); $_SESSION["itemcode"] = $itemcode_array; $_SESSION["prodname"] = $prodname_array; $_SESSION["pricedet"] = $pricedet_array; ?> There is some redundant and error testing code in there. The problem is $prodname_array; and $pricedet_array; are not being created even though $itemcode_array which is created the same way works fine. All values from the database are being displayed correctly (eg $row['prod_name']. Hi Guys, How can I send a session array through the URL and then use the values on the other page to create an SQL query? Any Ideas? Thanks in advance. Ed |