Jump to content

Recommended Posts

Hi there.

 

I feel like this is a no brainer for some, but I keep going back and forth with it and cannot seem to find the answer.

 

I want to use a session variable and push data into it as an array.  I am just pushing in row id's from a database.  I will need to reverse loop through this array for another function.  Can I add to a session without using the variable "$previouslyused" in the example below?

 

Here is what I mean.  Which is correct? Neither are working for me anyway, but I assume one of these is the more correct way..

 

<?php
session_start();

if (!isset($_SESSION['viewed'])) {
$previouslyviewed = array();
$_SESSION['viewed']= $previouslyviewed;
}

array_push($previouslyviewed, "$current_id");
?>

 

<?php
session_start();

if (!isset($_SESSION['viewed'])) {;
$_SESSION['viewed'];
}

array_push($_SESSION['viewed'], "$current_id");
?>

 

I'm still learning sessions...sorry if this is a no brainer...  Thanks!

Link to comment
https://forums.phpfreaks.com/topic/147488-looping-through-a-session-array/
Share on other sites

If I understand correctly I think this is what you want to do.

 

Find:

array_push($previouslyviewed, "$current_id");

 

Replace with:

array_push($_SESSION['viewed'], "$current_id");

 

Is that what you wanted to do?

 

 

 

actually yes, thanks...turns out I had a typo. Go figure!

just do

 

$_SESSION['current_id'] = $current_id;

 

that way you don't need to loop through anything

 

Well looping is required as far as I can see for what I'm doing.  Basically I want to have a button that when hit, will go backwards through the row id's from my table and load previous info in.  So the way I was working it was that the id's would be added to this array as normal use was going on, and then when I needed to hit the "previous" button, it would start going through the array from the last entry and back through...are you saying that there is an easier way?

ok according to your last post you're expecting to have a couple entries

 

if you're on entry 3

 

you want a previous and a next button which lead to 2 and 4 respectively.

 

and judging by your lingo ('row','table') you're using mysql..

 

so basically you could just do

 

<?php
  $op = (($_GET['act'] == 'next')? '>'($_GET['act'] == 'back')? '<':false));
  if ($op) {
    $qry = mysql_query("SELECT * FROM `theTable` WHERE `id` $op '{$_SESSION['current_id']}' ORDER BY `id` ASC LIMIT 1");
    if (mysql_fetch_assoc($qry)) {
      // show data;
    } else {
      // no data to show;
    }
  }
?>

ok according to your last post you're expecting to have a couple entries

 

if you're on entry 3

 

you want a previous and a next button which lead to 2 and 4 respectively.

 

and judging by your lingo ('row','table') you're using mysql..

 

so basically you could just do

 

<?php
  $op = (($_GET['act'] == 'next')? '>'($_GET['act'] == 'back')? '<':false));
  if ($op) {
    $qry = mysql_query("SELECT * FROM `theTable` WHERE `id` $op '{$_SESSION['current_id']}' ORDER BY `id` ASC LIMIT 1");
    if (mysql_fetch_assoc($qry)) {
      // show data;
    } else {
      // no data to show;
    }
  }
?>

 

wow...I'm not actually sure how to interpret your code, but I could imagine that if it does what you think I want it to do, it's much easier than what I have here..

 

It's a lot so, don't feel obligated to check it out, but actually what I'm doing is using one button to pull text randomly and insert it somewhere, which is repeated each time it is hit.  Then the previous button should go back through the ones that we already saw before we refreshed it with new ones.  Is that what your code does too?

 

I think I'm confused by what this line does:

 

  $op = (($_GET['act'] == 'next')? '>'($_GET['act'] == 'back')? '<':false));

 

My code: haha

<?php
session_start();

if (!isset($_SESSION['viewed'])) {
$_SESSION['viewed'];
}
?>

<?php

if ($_POST) {

$con = mysql_connect('server', 'user', 'password');
	if (!$con) {
  			die('Could not connect: ' . mysql_error());
  		}
$db_selected = mysql_select_db("form_sections",$con);
print "Connected Successfully<br /><br />";

if ($_POST['newText']) {
	$order_by_desc = "SELECT text, id, updated_at FROM para1 ORDER BY RAND() LIMIT 1";
	$reverseiterator = 1;
	print $order_by_desc;
	$find_oldest_result = mysql_query($order_by_desc,$con);
	$oldest_result_row = mysql_fetch_array($find_oldest_result);
	$form_fill = ($oldest_result_row['text']);
	$current_id = ($oldest_result_row['id']);
	array_push($_SESSION['viewed'], "$current_id");
}

elseif ($_POST['previousText']) {
	$reversed_array = array_reverse($_SESSION['viewed']);
		if ($reverseiterator = 1) {
			print "This is the first time we are moving backwards and the reverse iterator is: " . $reverseiterator . "<br />";
			$order_by_id = "SELECT text FROM para1 WHERE id =" . $reversed_array[$reverseiterator] . " LIMIT 1";
			$last_result = mysql_query($order_by_id,$con);
			$last_row = mysql_fetch_array($last_result);
			$form_fill = $last_row['text'];
			$current_id = ($last_row['id']);
			print $order_by_id . "<br /><br />";
		}
		else {
			$reverseiterator = $reverseiterator+1;
			print "This is a repeat time we are moving backwards and the reverse iterator is: " . $reverseiterator . "<br />";
			$order_by_id = "SELECT text FROM para1 WHERE id =" . $reversed_array[$reverseiterator] . " LIMIT 1";
			$last_result = mysql_query($order_by_id,$con);
			$last_row = mysql_fetch_array($last_result);
			$form_fill = $last_row['text'];
			$current_id = ($last_row['id']);
			print $order_by_id . "<br /><br />";
		}
}


elseif ($_POST['create']) {
	if (!empty($_POST['form1'])) {	
	$form1 = $_POST['form1'];
	mysql_query("INSERT INTO para1 (text, updated_at, id) VALUES ('$form1', NOW(), '$current_id')");
	print "Added!";
	}
}

$reversed_array = array_reverse($_SESSION['viewed']);
print "current id is " . $current_id . "<br /><br />";
print "current stamp is " . strtotime($oldest_result_row['updated_at']) . "<br /><br />";
print "previous id is " . $reversed_array[1] . "<br /><br />";

print_r($_SESSION['viewed']);
mysql_close($con);
}

else {
$form_fill = "nothing"; 
}

?>

			<input type="submit" name="newText" value="New Text" /> 
			<input type="submit" name="previousText" value="Previous Text" /> <br />

<?php
  $op = (($_GET['act'] == 'next')? '>'($_GET['act'] == 'back')? '<':false));
  if ($op) {
    $qry = mysql_query("SELECT * FROM `theTable` WHERE `id` $op '{$_SESSION['current_id']}' ORDER BY `id` ASC LIMIT 1");
    if ($row = mysql_fetch_assoc($qry)) {
      // show data;
    } else {
      // no data to show;
    }
  }
?>

 

added in $row = into the if statement so you could use $row to reference the data :)

 

you will still need to connect to the mysql server, select a mysql database, and this code will ofcourse work, if you fill in the correct data or use the data the right way, I don't write full scripts for people, I only guide people in the right direction.. unless ofcourse its a simple function which sounds fun enough to do, but this kinda pagination/database work is very common and simple enough for u to take my guidelines presented above and use it with your script..

<?php
  $op = (($_GET['act'] == 'next')? '>'($_GET['act'] == 'back')? '<':false));
  if ($op) {
    $qry = mysql_query("SELECT * FROM `theTable` WHERE `id` $op '{$_SESSION['current_id']}' ORDER BY `id` ASC LIMIT 1");
    if ($row = mysql_fetch_assoc($qry)) {
      // show data;
    } else {
      // no data to show;
    }
  }
?>

 

added in $row = into the if statement so you could use $row to reference the data :)

 

you will still need to connect to the mysql server, select a mysql database, and this code will ofcourse work, if you fill in the correct data or use the data the right way, I don't write full scripts for people, I only guide people in the right direction.. unless ofcourse its a simple function which sounds fun enough to do, but this kinda pagination/database work is very common and simple enough for u to take my guidelines presented above and use it with your script..

 

Totally understandable.  I prefer to try and understand the code rather than have someone do it for me anyway.  Thanks for this!  I'm gonna play around with it :-)

also good to note that I set it up so that the script waits for ?act=next or ?act=back

 

so your next and back arrows just make them point to whatever.php?act=next and whatever.php?act=back respectively :)

 

and uses the current_id from the session

 

$_SESSION['current_id'];

 

basically what the query does is orders the results by `id` (if it isn't already), and then finds the next greatest (>) or the next lowest (<)

 

although now thinking about it the context of the statement WHERE `id` > CURRENT_ID

 

would probably look for the next lowest..

 

so you might need to change the $op declaration around so '>' is '<' and '<' is '>' but idk :)

 

hope I'm helping

 

 

also good to note that I set it up so that the script waits for ?act=next or ?act=back

 

so your next and back arrows just make them point to whatever.php?act=next and whatever.php?act=back respectively :)

 

and uses the current_id from the session

 

$_SESSION['current_id'];

 

basically what the query does is orders the results by `id` (if it isn't already), and then finds the next greatest (>) or the next lowest (<)

 

although now thinking about it the context of the statement WHERE `id` > CURRENT_ID

 

would probably look for the next lowest..

 

so you might need to change the $op declaration around so '>' is '<' and '<' is '>' but idk :)

 

hope I'm helping

 

Oh I see what you're saying.  What I'm wondering though, is how it keeps track of which ID's were used already?  I am not moving back and forth through the table just by ID.  I am pulling rows randomly. So, won't this script basically find the ID I am currently on, and then move up and down the table according to ID?  I need it to know the history of what was called before since it is not in such an order.  You know what I'm saying?

well then, add all the used ids to a session  variable like

 

$_SESSION['used'][] = $_SESSION['current_id'];

 

then when you select a random one

 

do

 

"... WHERE `id` NOT IN (".implode(",",$_SESSION['used']).") ..."

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.