helloworld001 Posted February 6, 2015 Share Posted February 6, 2015 I am having a bit of issue. I have a simple query that loops to find each record, like this. // select query here if(count($result) > 0) { foreach($result as $row) { $userid = $row['user_id']; $_SESSION['userid'] = $userid; } } else { // error here } I want to use the "$userid" on a different page; so I created a session for it. When ever I use that session on another page, it gives me only the last record's user id and not the first one. How can I fix this? Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/ Share on other sites More sharing options...
Ch0cu3r Posted February 6, 2015 Share Posted February 6, 2015 You are getting the last user id value because $_SESSION['userid'] is being overwritten as you iterate over $result If all you want is the first user id then why are you using a loop? You could just do something like $_SESSION['userid'] = $result[0]['userid']; // add the first userid value to session Or better yet reconstruct your query so it only returns the data you want. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505124 Share on other sites More sharing options...
helloworld001 Posted February 6, 2015 Author Share Posted February 6, 2015 You are getting the last user id value because $_SESSION['userid'] is being overwritten as you iterate over $result If all you want is the first user id then why are you using a loop? You could just do something like $_SESSION['userid'] = $result[0]['userid']; // add the first userid value to session Or better yet reconstruct your query so it only returns the data you want. I should mention that I want ALL user ids in that session. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505127 Share on other sites More sharing options...
CroNiX Posted February 6, 2015 Share Posted February 6, 2015 $_SESSION['userid'][] = $userid; //add userid to array instead of overwriting it Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505128 Share on other sites More sharing options...
helloworld001 Posted February 6, 2015 Author Share Posted February 6, 2015 $_SESSION['userid'][] = $userid; //add userid to array instead of overwriting it your example gives me this error. Fatal error: [] operator not supported for strings Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505129 Share on other sites More sharing options...
Ch0cu3r Posted February 6, 2015 Share Posted February 6, 2015 Initiate $_SESSION['userid'] to an array outside the foreach loop $_SESSION['userid'] = array(); foreach($result as $row) { ... Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505131 Share on other sites More sharing options...
CroNiX Posted February 6, 2015 Share Posted February 6, 2015 if(count($result) > 0) { $ids = array(); //store ids in a separate array foreach($result as $row) { $ids[] = $row['user_id']; } $_SESSION['userid'] = implode(',', $ids); //turn the array of IDs into a comma separated string } Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505132 Share on other sites More sharing options...
helloworld001 Posted February 6, 2015 Author Share Posted February 6, 2015 if(count($result) > 0) { $ids = array(); //store ids in a separate array foreach($result as $row) { $ids[] = $row['user_id']; } $_SESSION['userid'] = implode(',', $ids); //turn the array of IDs into a comma separated string } That works great. Now there is only 1 other issue. On process.php page I have a query that selects records using the above user_id. It looks like this. $userid = $_SESSION['userid'][]; $stmt = $db->prepare("SELECT user_id FROM records WHERE user_id = :user_id"); $stmt->bindParam(':user_id', $userid); For some reason, the my session above gives me this error. Fatal error: Cannot use [] for reading Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505134 Share on other sites More sharing options...
CroNiX Posted February 6, 2015 Share Posted February 6, 2015 $userid = $_SESSION['userid'][]; What's the extra [] for? There isn't "a" user id. You said you wanted ALL user ids. $_SESSION['userid'] is now a string of comma separated IDs that now looks like: 1,2,5,6,7,8,[...]. But, your query below makes no sense. $stmt = $db->prepare("SELECT user_id FROM records WHERE user_id = :user_id"); So if the user_id is 1, you will just get back 1, which is what you started with. What's the point of that? I think you need to give us more of the big picture on what you're trying to accomplish with the code you're having problems with. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505136 Share on other sites More sharing options...
helloworld001 Posted February 6, 2015 Author Share Posted February 6, 2015 (edited) $userid = $_SESSION['userid'][]; What's the extra [] for? There isn't "a" user id. You said you wanted ALL user ids. $_SESSION['userid'] is now a string of comma separated IDs that now looks like: 1,2,5,6,7,8,[...]. But, your query below makes no sense. $stmt = $db->prepare("SELECT user_id FROM records WHERE user_id = :user_id"); So if the user_id is 1, you will just get back 1, which is what you started with. What's the point of that? I think you need to give us more of the big picture on what you're trying to accomplish with the code you're having problems with. Alright let me clarify it. I have 2 pages. records.php and process.php . On records.php, I have this code where It retrievs records from database and shows them on the page. It also has ajax in the head, that uses process.php url <?php require_once 'core/init.php'; ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <script src="js/jquery-1.11.0.min.js"></script> <script> $(document).ready(function(){ function showTrade(){ $.ajax({ type:"post", url:"process.php", data:"action=showRecord", success:function(data){ $(".show-records").html(data); } }); } showTrade(); $(".record-button").click(function(){ $.ajax({ type:"post", url:"process.php", data:"action=addRecord", success:function(data){ showTrade(); } }); }); }); </script> </head> <body> $getCategoryId = escape($_GET['id']); try { // Find out how many items are in the table $stmt_get = $db->prepare("SELECT COUNT(*) FROM records WHERE category_id = :category_id"); $stmt_get->bindParam('category_id', $getCategoryId); $stmt_get->execute(); $total = $stmt_get->fetchColumn(); // How many items to list per page $limit = 10; // How many pages will there be $pages = ceil($total / $limit); // What page are we currently on? $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array( 'options' => array( 'default' => 1, 'min_range' => 1, ), ))); // Calculate the offset for the query $offset = ($page - 1) * $limit; // Some information to display to the user $start = $offset + 1; $end = min(($offset + $limit), $total); if($page > 0) { $offset = ($page - 1) * $limit; } else { $offset = 0; } $stmt = $db->prepare("SELECT records.*, categories.* FROM records LEFT JOIN categories ON records.category_id = categories.category_id WHERE records.category_id = :category_id ORDER BY record_id DESC LIMIT {$limit} OFFSET ".$offset); $stmt->bindParam('category_id', $getCategoryId); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if(count($result) > 0) { $ids = array(); //store ids in a separate array foreach($result as $row) { $record_id = escape(intval($row['record_id'])); $userid = escape($row['user_id']); $category_id = escape(intval($row['category_id'])); $category_name = escape($row['category_name']); $ids[] = $userid; ?> <div class="record-a"> <?php echo $username; ?> <form action="" method="post" enctype="multipart/form-data"> <input type="button" name="submit" class="record-button" value="Trade Item"> </form> </div> <?php } $_SESSION['requestTo'][] = $ids; } else { $error = 'There are no records on this page.'; } } catch(Exception $e) { die($e->getMessage()); } ?><div class="show-records"></div><?php require 'snippets/pagination.php'; </body> </html> On process.php page is the following code. This code is used through ajax when I click submit button in the above form(#record-a div). All I want to do is get the unique user_id for each record created and use that user_id on this page. <?php require_once 'core/init.php'; $user = new User(); $mainUseri = escape($user->data()->user_id); $userid = $_SESSION['requestTo']; $action = $_POST['action']; if($action == "showRecord") { try { $stmt = $db->prepare("SELECT request_by, request_to, session FROM drop_session WHERE request_by = :request_by AND request_to = :request_to AND session = :session"); $stmt->bindParam(':request_by', $mainUserid); $stmt->bindParam(':request_to', $userid); $stmt->bindValue(':session', 1); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if(count($result) > 0) { ?> <div class="new-window-content"> Waiting for user <?php echo $userid; ?> </div> <?php } else { $error = 'There was a problem.'; } } catch(Exception $e) { die($e->getMessage()); } ?> <span class="error"><?php echo $error; ?></span> <span class="success"><?php echo $success; ?></span> <?php } else if($action == "addRecord") { try { $find = $db->prepare("SELECT request_to, session FROM drop_session WHERE request_to = :request_to AND session >= :session"); $find->bindParam(':request_to', $userid); $find->bindValue(':session', 1); $find->execute(); $resultFind = $find->fetchAll(PDO::FETCH_ASSOC); if(count($resultFind) > 0) { $error = 'Trade in progress. Please try later.'; } else { $stmt = $db->prepare("INSERT INTO drop_session(request_by, request_to, session) VALUES(:request_by, :request_to, :session)"); $stmt->bindParam(':request_by', $mainUserid); $stmt->bindParam(':request_to', $userid); $stmt->bindValue(':session', 1); $stmt->execute(); if($stmt == false){ $error = 'There was a problem.'; } else { $success = 'Trade success.'; } } } catch(Exception $e) { die($e->getMessage()); } ?> <span class="error"><?php echo $error; ?></span> <span class="success"><?php echo $success; ?></span> <?php } else { echo 'something went wrong'; } Edited February 6, 2015 by helloworld001 Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505137 Share on other sites More sharing options...
helloworld001 Posted February 8, 2015 Author Share Posted February 8, 2015 So does anyone have a solution? If you need further clarification to understand what I am trying to do, please ask. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505165 Share on other sites More sharing options...
mac_gyver Posted February 8, 2015 Share Posted February 8, 2015 So does anyone have a solution? a solution to what? you started this thread with a snippet of code that lacked any context upon which to help you with what you eventually stated that piece of code should be doing and the code you finally posted, which contains at least two php errors and won't run at all, doesn't have the specific things in it you have been asking about. keeping in mind that we ONLY SEE the information that you supply, at this point we don't know what code you tried with the things in it you have asked about or what symptom or errors you got from that code that you need help with. go back and reread everything in this thread, from the point of view of someone that only knows what your code, data, and symptoms are from the information that's posted in this thread. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505179 Share on other sites More sharing options...
Solution helloworld001 Posted February 8, 2015 Author Solution Share Posted February 8, 2015 a solution to what? you started this thread with a snippet of code that lacked any context upon which to help you with what you eventually stated that piece of code should be doing and the code you finally posted, which contains at least two php errors and won't run at all, doesn't have the specific things in it you have been asking about. keeping in mind that we ONLY SEE the information that you supply, at this point we don't know what code you tried with the things in it you have asked about or what symptom or errors you got from that code that you need help with. go back and reread everything in this thread, from the point of view of someone that only knows what your code, data, and symptoms are from the information that's posted in this thread. I suppose I could have tried to explain it better in the begining. None the less, I have found a different solution to my problem. Thank anyways. Quote Link to comment https://forums.phpfreaks.com/topic/294437-need-help-with-using-session-outside-foreach-loop/#findComment-1505199 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.