Page 1 of 1

if mysql select returns no results redirect

Posted: Wed Dec 15, 2010 7:55 pm
by mfandel
First time using a DB(MYSQL) and php to produce a little search.
I have a list of zip codes for sales reps. The intial search worked great, but I want to have an if/else so if someone enters a zip code that is not in my database they are taken to a different page or recieve a message.

Not haveing much luck.

Here is the code I have and need the code help for if the zip is not in the database... beable to post text or link to a page:

Code: Select all

<?php
mysql_connect ("localhost", "peterson_galiant","p3t3rs0n")  or die (mysql_error());  
mysql_select_db ("peterson_zipcode"); 
$term = $_POST['term'];  
$sql = mysql_query("select * from reps_zip where zip like '%$term%'");  
while ($row = mysql_fetch_array($sql)){   
	echo '<img src="'.$row['picture'].'" width=274>'; 
	echo '<br/>'.$row['name'];  
	echo '<br/> <a href="'.$row['page'].'">Contact Info</a>'; 
	echo '<br/><br/>';  
} 
?>

Re: if mysql select returns no results redirect

Posted: Thu Dec 16, 2010 1:09 am
by social_experiment
Depending on your primary key field, you can count the rows that is returned by a search.

Code: Select all

<?php
 // in this example, id is the PK
 $count_query = mysql_query("SELECT COUNT(id) FROM reps_zip 
 WHERE zip like '%$term%' ");
 //
 $array = mysql_fetch_array($count_query);
 // the result of the above is in the first value of
 // the array
 $rows = $array[0];

 if ($rows == 0) {
  // here you will probably use a function because
  // you might get a 'headers already sent error 
  // message
  header('redirect: otherpage.php');
  }
  else {
   // here the value is indeed in your table so continue
   // as normal
   $sql = mysql_query("select * from reps_zip where zip like '%$term%'");  
  }
?>