php get, random records, and the back button - php

My site has a library full of games, nations, game scenarios, etc.
library.php is given a type=___ & id=___
for example library.php?type=scenario&id=ABCD001
library.php saves the id to a session variable and loads an include appropriate for the type
This all works just dandy. Now, I wanted to give my users the option of pulling up a random scenario. To do that, I added a special id to the logic within lib-scenario.php (the include) such that if given library.php?type=scenario&id=random the include knows to run an alternate query for a random record rather than for the actual id
This also works just dandy... unless someone hits the Random Scenario button two+ times in a row, and decides that the previous random scenario was way cooler, I want to go back to that.
Because the http address is always directory/library.php?type=scenario&id=random no matter how many times you click Random Scenario, as soon as you click back you'll be taken to the last page with an alternate address you visited.
So, if you start at the Home page, and hit Random Scenario 35 times, then decide the 34th one was what you wanted and click BACK, you'll be put back onto the Home page.
I must admit this was not a problem I had anticipated. One of my testers was the first to have the urge to back-up in the random scenario stream and here we are.
How can I add back-up functionality to my script?

Make the 'Random Scenario' button simply link to an actual (but random) scenario id. You'll probably have to construct this with an SQL query to get all the id's of your scenarios.
$result = mysql_query("SELECT id FROM scenarios");
while ($row = mysql_fetch_row($result)) {
$ids[] = $row[0];
}
$randomid = array_rand($ids);
Button:
<a href="directory/library.php?type=scenario&id=<?php echo $randomid; ?>Random Scenario</a>
If your scenario id's are all consecutive numbers you can simply use this instead:
$randomid = rand($min, $max);

you can resolve this by redirecting to the canonical url for the scenario, i.e.: id=random redirects to id=A92831 or whatever was selected. the final url will be stored in the history, rather than the id=random url.

Related

Making sure users go through all set up pages in order

Users will enter information on 4 separate pages and click a 'continue' button that takes them to the next page.
I know I shouldn't prevent users from going back and entering information again, but I also need to set up something that doesn't allow users to do something like this:
www.page.com/setup1 -> www.page.com/setup3 -> www.page.com/setup4 -> www.page.com/setup2
Right now they could possibly go in any order they want if they just enter the URL.
$URL = $_SERVER["HTTP_REFERER"];
if($URL == "http://page.com/setup1") { blah blah }
I have a variable that handles the page that they came from, displaying certain information based on that. Is there a way to use that variable to handle my issue? If not, what is the best way to tackle this issue that might arise?
Instead of using four pages, write one and work with JQuery which enables you to show and hide successive fields etc. Use Ajax calls to provide any dynamic information such as selectors based on previous answers. Those can populate DIVs or SPANs which carry hidden default responses . There is at least one excellent Validate plugin that works with JQuery so you ensure all fields are correctly completed.
The advantages are an enhanced user experience, faster responses with reduced server load. It also means that if they want to change earlier data you can handle it all via Ajax and a good plan.
Before adopting the above approach, I used to use one framework page to post back to itself using hidden fields to control the flow, passing data with increasing numbers of post variables and nested if's. I made it managable with lots of include files to do the updates and new fields
My issue was solved through session variables. Each page has a session variable called 'steps'. Each step has a number associated with the page that they are on. If they previous session 'step' was not the correct one, it redirects them to the appropriate 'step' page.
$steps = $_SESSION['steps'];
$_SESSION['steps'] = 3
For example, this must be the 3rd page, or 'step' in the sign up process.
If $steps isn't == 3, I have code that redirects them to the start of the sign up process, destroys the session and they must sign up properly.

Moving through Detail Pages of Recordset

My website allows visitors to search for homes (using PHP and MySql). After the search, they are presented with a list of matches which they can click on to see the detail page for that home. To see the next home, they currently have to click back, then click on the next home in the search results list they want to view.
I would like to make it so that once they have clicked on one home to view the details, they would have a "Next Home" and "Previous Home" link/button to use to navigate the results set without having to go back to the search results page.
I've seen this done, but can't get my head around how to do it. I assume you have to save the recordset from the initial search somewhere, and then recall it on the details page. And you'd have to know that you were looking at the xth home out of Y homes.
Can anyone give me a broad overview of how this would work? Do I save the initial search results in a temp MySQL table and pass that table name to the details page? Or use a session variable to hold the results set? Keep in mind that a visitor could make several different searches during their session.
Any assistance would be most appreciated,
Tom
When I've done this, I've saved the details of the current search in SESSION, and then requeried the database when I've needed to - so you can query it on the detail page to generate a Next and Previous link, and so on. I normally use a SESSION variable called 'parameters', and add the whole of the SQL WHERE statement to it.
If someone's making multiple searches, this will let them make one at a time - subsequent searches will over-write what's already in there. If your users are going to be making multiple searches at the same time using different parameters, you'll need to find a way to differentiate the parameters for each search. You can give each set a unique name by prefixing it with a call to uniqid, and you'll then need to make sure you pass the unique identifier to the detail page, so it can work out which set of parameters it needs to run.

Creating "came-from" navigation - PHP

I was wondering, how is it possible to get example the last X number of pages a user came from on my site?
I am creating a navigation, so the user easily can see the X number of previuos pages he visited on my site only.
I just don't know how to do this. Is there any function in PHP to obtain this?
Thanks in advance.
I'm assuming you mean the last X pages on your site only, and that you know how to use sessions and arrays.
In this case you could initialize a session for the user, then every time the user visits a page, append the URL or some identified of that page to the array. If there's more than X pages in the array, additionally remove the first one.
Then you could just get the contents of the array, parse them into a bunch of links and show them on your site.
In case you meant the pages before entering your site, you can only get the latest one via the referer header. Some browsers might be configured to not send the referer header, however, so there really isn't a way of accomplishing this properly.
<?php
session_start();
/*
Put here any logic that could result in a redirect, to avoid useless records
...
*/
$_SESSION['history'][] = $_SERVER['REQUEST_URI'];
$_SESSION['history'] is now an indexed array with all of the user's history on your website.

PHP redirect/hit counter

I'm trying to figure out how to count the number of views that have been sent to my site from another website. I have a banner advertised and I want to have the banner link directed to a php script that will count the number of times people from website abc.com vistied the site.
The question is how do I go about doing this? I was thinking about setting up a table in mysql with a different row for each site and then have that specific row increment the count by one.
Problem is I'm not sure how to use the function i++ (if thats even right function). I am new to php, sorry if what I'm asking is a basic thing
You can get the referrer from $_SERVER['HTTP_REFERER']. It doesn't always exist so you'd need to check, and if it does then perform an upsert.
I would do something like this:
   
if(isset($_SERVER['HTTP_REFERER'])){
$referrer = $_SERVER['HTTP_REFERER'];
$query = "INSERT INTO 'referrals'
('referrer', 'count')
VALUES
($referrer, 1)
ON DUPLICATE KEY UPDATE
'count' = 'count' + 1";
$result = mysql_query($query);
}
Usually banners point to a specific URL on your server from the referring website so you can track where things come from.
Eg: BigSite.com has a banner for you that links to MySite.com/links/01941731.htm
Using something like .htaccess on an Apache server you can parse the incoming "01941731" part, safely check it against your database and incremement the key it relates to so that it counts against an incoming link from BigSite.com
Thats how I would do it :)

What would be a good way to direct users to different URLs from one link?

I've been working with PHP for a few months now. I've put together a small PHP site with three groups of users: admin, teacher, students.
Here's what I would like to do:
Students are in different groups. I have five different groups now. Each one of these five groups has access to a link that directs them to an online classroom. We can have a variable number of classrooms.
Let's say we have five classrooms for Group 1.
Let's say that 20 students from Group 1 click on a link at 5:00p.m. This link brings them to an online classroom. I would like the first five students to be redirected to one classroom/link, the second five students redirected to another classroom/link, the third five students redirected to another classroom and so on.
My questions is, would it be best to do this in PHP? JavaScript? Is this overly complicated or actually quite trivial?
Cheers!
Sam
This is best to be done in the server side. Give them all the same link. On the page / PHP file behind the link hold a counter which counts the times that the link is requested. Based on the count, redirect to the desired page using the location header.
The problem here is that you need some server-side state to make this happen, i.e. a counter of some kind that is stored on the server.
You also need to be careful that this counter can be locked from read until update, or else your numbers will be off. If several people click the link close together, they may all read the same counter value, and you could end up with more than 5 people in a classroom.
Well, assuming that you are storing the number of people that have clicked the link so far in a database:
// Get the number of people who clicked from a database or somewhere
$people_clicked = getCurrentNumber();
// Update the Number in the Database ASAP (As per comments)
updateNumber();
// Divide it by room number
// Make sure it is a whole number
$room = floor($people_clicked/5);
// Define each room into an array
$room_links = array("http://firstroom.com", "http://secondroom.com");
// Redirect
// This redirects people 1-5 to the first item in the array, 6-10 to the second, etc.
header("Location: ".$room_links[$people_clicked]);
Basically, you have the link redirect to a page. The page grabs the number of people that have clicked on the link so far. Then you find out which classroom they are going to, and then update the number in the database. Finally, redirect them to the correct location.
There is a lot of open room, but those are the basic steps.
Also, as the comments said, you might want to read/write the number at the same time in order to assure that it is written as close to the call as possible. You might want to to lock the counter on the DB in some fashion, and if the script encounters a locked, sleep for a second and try again.
I would define the problem in terms of an array of "seats", and search through the array to find the next available seat.
$seat[0] => 'link1';
$seat[1] => 'link1';
etc.
$seat[4] => 'link1';
$seat[5] => 'link2';
$seat[6] => 'link2';
etc.
That way when a student leaves a classroom, the seat is free for the next student. This minimizes the required number of classes (bandwidth).

Categories