使用PHP和MySQL进行随机URL重定向

时间:2013-05-14 20:56:35

标签: php mysql database random

我有一个问题,即在我的网站上添加一个链接,当点击“'将用户发送到存储在 MySQL数据库中的随机网址。

我的数据库名为" movie"我希望能够让用户点击一个链接,它会将它们发送到我的数据库中存储的一个电影页面URL。

EX:用户点击"随机"链接并从我的数据库中获取电影页面(我有大约110个URL列出了唯一的ID)。

我会使用类似的东西吗?

  • 标题('位置:' xxxxx);

要做到这一点吗?

我知道我应该能够使用PHP完成这项任务,我只是难以解决这个问题。任何帮助都会很棒!感谢。

2 个答案:

答案 0 :(得分:0)

我假设您发布的查询选择了一个随机电影,并且存储网址的字段称为“网址”。

$result = mysql_query("SELECT url FROM movie ORDER BY RAND() LIMIT 0, 10")
                  or die(mysql_error());

$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);

这应该重定向到数据库中的url。

答案 1 :(得分:0)

试试这个:

mt_rand("", ""); // this creates random numbers and use it in a variable as:
$id= mt_rand("1", "110");
// hatever id number is generated it will put out that one in the query but it is only for one if you want multiple put $id in a for loop  than print the result in while loop.
$result = mysql_query("SELECT url FROM movie WHERE id= '$id' LIMIT 0, 10")
                  or die(mysql_error());

$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);