开发者

redirect/echo if file.php?id=* not found/doesn't exist

开发者 https://www.devze.com 2023-02-03 13:51 出处:网络
Hey guys, PHP and MySQL newguy here. 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/1437

Hey guys, PHP and MySQL newguy here. 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

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'. I though about us开发者_如何学Pythoning the if command, but couldn't figure out the syntax. 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. 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.


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. 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.

if that query returns any results (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.


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.

if (mysql_num_rows($result)==0){
    echo "There are no rows with this id";
}else{
     // Your normal code
}
0

精彩评论

暂无评论...
验证码 换一张
取 消