Jump to content

[SOLVED] Using 'if' clause to redirect


dannyluked

Recommended Posts

Hi,

I have 3 php scripts on the same page, all working fine. They all contain an 'if' clause. The only problem is that all the scripts work off the website URL (example.com/index.php?id=1) using the $_GET clause. In my first script (the main script) if the id in the URL isn't in the MySQL table it says 'no such record'. I would like it to instead redirect to my site homepage. Could anyone point me in the right direction to do this?

 

I mainly want to do this because under the scripts I have a form with a hidden field that inserts the id to a table. I dint want it too insert as the ID isn't used yet!

 

Idearly I would like the redirection script to be in the echo instead of the current code (There is no record of the ID ".$_GET['id'].").

 

Current script:

<?php
   include "config.php"; 
   mysql_connect($server, $db_user, $db_pass) or die (mysql_error());
   $result = mysql_db_query($database, "
select *, count(title) AS amountblog
FROM blog
WHERE id = '".$_GET['id']."'") or die (mysql_error());

$qry = mysql_fetch_array( $result ) ;
$numblogs = $qry[amountblog];
if($numblogs>0){
echo "";
}else{
  echo "There is no record of the ID ".$_GET['id']."<br><br>";
}
?> 

Link to comment
https://forums.phpfreaks.com/topic/168865-solved-using-if-clause-to-redirect/
Share on other sites

Hi

 

Just using header to redirect it:-

 

<?php
include "config.php"; 
mysql_connect($server, $db_user, $db_pass) or die (mysql_error());
$result = mysql_db_query($database, "
	select *, count(title) AS amountblog
	FROM blog
	WHERE id = '".$_GET['id']."'") or die (mysql_error());

$qry = mysql_fetch_array( $result ) ;
$numblogs = $qry[amountblog];
if($numblogs>0)
{
echo "";
}
else
{
header('Location:homepage.php');
exit;
}
?>

 

Note that you cannot do this if you have already sent anything to the screen (echo or even just a blank line before your first <?php tag).

 

Also note that using $_GET['id'] directly in the SQL is an open invitation to an SQL injection attack.

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.