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

痞子三分冷 提交于 2019-12-25 10:02:32

问题


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!


回答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" );



回答2:


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()




回答3:


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" );


来源:https://stackoverflow.com/questions/10006205/how-can-i-make-a-link-load-a-random-php-id-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!