我有一个 URL 缩短器脚本,它让用户提供记录 ID,然后重定向他们。但是,如果用户搜索的记录不存在,我希望能够将用户重定向到特定页面。我该怎么做?
我当前的代码是:
<?
mysql_connect("localhost","username","password");
mysql_select_db("database");
$sql="select * from shortened where (shortened.id='".mysql_real_escape_string($_GET['url'])."')";
$query=mysql_query($sql);
while($row = mysql_fetch_array($query)){
header('Location:'.$row['url']);
}
?>
我希望人们能够理解我要描述的内容。
最佳答案
放
if (!mysql_num_rows($query)) {
header('Location: http://google.com');
exit;
}
就在你的 while
部分之前
而你的 while
实际上可以重写为:
$row = mysql_fetch_array($query);
header('Location:'.$row['url']);
(是的,只需删除 while
- 在这种情况下毫无意义)
关于php - 如果记录不在数据库中则重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9041778/