DexCurl
DexCurl

Reputation: 1703

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

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 using the if command, but couldn't figure out the syntax. I also looked around the web, but no avail.

Thanks guys

Upvotes: 0

Views: 3554

Answers (3)

lonesomeday
lonesomeday

Reputation: 237905

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.

Upvotes: 3

Jose Armesto
Jose Armesto

Reputation: 13749

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
}

Upvotes: 0

Ross
Ross

Reputation: 17977

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.

Upvotes: 0

Related Questions