Jump to content
helloworld001

Need help with using session outside foreach loop

Recommended Posts

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?

 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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. 

Share this post


Link to post
Share on other sites

$_SESSION['userid'][] = $userid; //add userid to array instead of overwriting it

Share this post


Link to post
Share on other sites
$_SESSION['userid'][] = $userid; //add userid to array instead of overwriting it

 

your example gives me this error.

Fatal error: [] operator not supported for strings 

Share this post


Link to post
Share on other sites

Initiate $_SESSION['userid'] to an array outside the foreach loop

$_SESSION['userid'] = array();
foreach($result as $row) {
...

Share this post


Link to post
Share on other sites

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
}

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

$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.

Share this post


Link to post
Share on other sites

$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 by helloworld001

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.