Callum Whyte
Callum Whyte

Reputation: 2429

Redirecting user if record isn't in database

I have a URL shortener script that makes the user provide the record ID then redirects them. However, I want to be able to redirect the user to a specific page if the record they searched for does not exist. How can I do this?

My current code is:

<?

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']);
}

?>

I hope people can understand what I'm trying to describe.

Upvotes: 1

Views: 1036

Answers (3)

James L.
James L.

Reputation: 4097

How about this?

<? 
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);

if(mysql_num_rows($query) > 0){
    $row = mysql_fetch_array($query);
    $url = $row['url'];
} else {
        $url = "http://othersite.com";

}
header("Location: $url");

?>

Upvotes: 1

Abdul Basit Ansari
Abdul Basit Ansari

Reputation: 71

<?

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);

$row = mysql_fetch_array($query)

header('Location:'.$row['url']);


?>

while loop is no necessary here

Upvotes: 1

zerkms
zerkms

Reputation: 255155

Put

if (!mysql_num_rows($query)) {
    header('Location: http://google.com');
    exit;
}

right before your while part

And your while could be actually rewritten as:

$row = mysql_fetch_array($query);
header('Location:'.$row['url']);

(yes, just remove while - it is pointless in this case)

Upvotes: 2

Related Questions