[英]redirect/echo if file.php?id=* not found/doesn't exist
Hey guys, PHP and MySQL newguy here. 大家好,PHP和MySQL newguy在这里。 Wrote this php file which display the content of a row relative to the ID stated in the URL ( eg row 3 is file.php?id=3 ), heres the source: http://pastie.org/1437017 编写了这个php文件,该文件显示相对于URL中指定的ID的行内容(例如,第3行是file.php?id = 3),此处为源: http : //pastie.org/1437017
If I goto an id to which the relative row does not exist (eg .php?id=99999999999999), what do I put to in to get it to redirect to another page or echo 'FAIL'. 如果我转到一个相对行不存在的ID(例如.php?id = 99999999999999),我应该输入什么来使其重定向到另一个页面或回显“ FAIL”。 I though about using the if command, but couldn't figure out the syntax. 我虽然要使用if命令,但无法弄清楚语法。 I also looked around the web, but no avail. 我也环顾了网上,但无济于事。
Thanks guys 多谢你们
You have the following line: 您有以下几行:
$name=mysql_result($result,$id,"name");
If there is no row with the id $id
, $name
will be false
. 如果没有ID $id
行,则$name
将为false
。 You could therefore do the following: 因此,您可以执行以下操作:
if (!$name) {
header('Location: http://yoururl.com');
die();
}
Better yet would be to modify your query to this: 更好的办法是将查询修改为此:
$query="SELECT * FROM likes where id=$id";
and then do 然后做
if (!$num) {
header('Location: http://yoururl.com');
die();
}
where $num
is the number of row returned, as set in your existing code. 其中$num
是您现有代码中设置的返回的行数。
Edit As noted elsewhere in this question, it is probably better to serve a 404 Not Found
page with appropriate content, rather than redirecting to another page. 编辑如该问题的其他地方所述,最好为404 Not Found
页面提供适当的内容,而不是重定向到另一个页面。 I can just about imagine a situation where redirection is appropriate, but if your redirection page says "item not found", this is the wrong approach. 我可以想象一个合适的重定向情况,但是如果您的重定向页面显示“找不到项目”,那么这是错误的方法。
I'd redesign your query to something like 我会将您的查询重新设计为类似
SELECT * FROM table WHERE id = $id;
where $id is the $_GET value - sanitised of course. 其中$ id是$ _GET值-当然已经过处理。
if that query returns any results (mysql_num_rows($result)==1)
如果该查询返回任何结果(mysql_num_rows($result)==1)
then you know a valid record has been found. 那么您知道已找到有效记录。 If not, the id doesn't exist, so you can throw an error/redirect. 如果不存在,则该ID不存在,因此您可以引发错误/重定向。
mysql_num_rows() gives you the number of rows in your select, so if that value is 0, you know there isnt any row with that given id. mysql_num_rows()为您提供选择的行数,因此,如果该值为0,则说明没有任何具有给定id的行。
if (mysql_num_rows($result)==0){
echo "There are no rows with this id";
}else{
// Your normal code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.