How can I make a link load a random php ID on the page?

Go To StackoverFlow.com

0

Database row IDs are tied to the URLs like this:

The page for row 2 becomes site.com/index.php?id=2

If I manually refresh index.php it displays a random record, but naturally it doesn't display the record ID in the address bar.

Is there a way to make a link display a random record while showing the id change in the address bar?

Thank you for your help!

2012-04-04 06:49
by karhu


1

Instead of just showing the random record, choose the record's id and do a redirect to the version that shows the id.

$randomId = // whatever method you use to choose it
header( "Location: http://site.com/index.php?id=$randomId" );
2012-04-04 06:53
by JJJ
Kiitoksia, Juhana. This works well (because a random ID is eventually shown in the URL bar), but it's causing a redirect loop (310) when I run it and the page doesn't load. Do you know how to correct this? Thanks - karhu 2012-04-04 07:22
Make sure you're doing the redirect only when the id isn't specified (!isset( $_GET[ 'id' ] )) - JJJ 2012-04-04 07:26
Brilliant. It's working now. Thank you for all of your help - karhu 2012-04-04 07:37


1

Try this :

$randomId = rand(0,100); // if let's say your post IDs go from 0 to 100
header( "Location: http://www.yourdomain.com/post.php?id=$randomId" );
2012-04-04 06:56
by Dr.Kameleon


1

There are multiple ways to do this.

You could like Juhana said, using the header function. This wil redirect you to another page by pagereloading.

You could use HTML5 to change the addressbar without pagereloading by using the window.history and jQuery for AJAX.

The safest option is the PHP header function. Keep in mind to NOT print/echo anything before you header. In case you still get "headers already sent" use ob_clean()

2012-04-04 07:12
by Ron van der Heijden
Ads