Jump to content


Photo

How to tell if there are no results returned give an error


  • Please log in to reply
3 replies to this topic

#1 ivalea

ivalea
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 09 October 2006 - 05:44 PM

Hello,

I'm trying to pull customers first name and last name from mysql.  What I want to do is say if there is no result returned then either echo an error message or redirect to another page.  But what I have now , lets the user into the page whether they are found in the table or not. All I'm trying to do is get the customers first and last name but only if their email address is found in the students table.  Here is what I have:

$result = mysql_query("SELECT customers.customers_firstname, customers.customers_lastname from customers, students where students.students_email = customers.customers_email_address") or die (mysql_error());
if(!result){
echo 'None';
}else{
while ($row = mysql_num_rows($result)) 
{ 
$first .= $row[ 'customers_firstname' ]; 
$last .= $row[ 'customers_lastname' ]; 
}
}

This returns a server error when running the script...  Any thoughts on how I can achive this correctly?  Thanks! :)

#2 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 09 October 2006 - 05:50 PM

if(mysql_num_rows($result))
{
	while($row = mysql_fetch_assoc($result))
	{
		// do stuff
	}
}
else {
	echo "No such customer";
}


#3 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 09 October 2006 - 05:52 PM

You need to test whether the number of rows returned by the function mysql_num_rows() is greater than 0.

Here's my take on your code:
<?php
$q = "SELECT customers.customers_firstname, customers.customers_lastname from customers, students where students.students_email = customers.customers_email_address";
$result = mysql_query($q) or die ("Problem with the query: $q<br>" . mysql_error());
if(mysql_num_rows($result)) echo 'None';
else{
    while ($row = mysql_fetch_asssoc($result)) { 
         $first .= $row[ 'customers_firstname' ]; 
         $last .= $row[ 'customers_lastname' ]; 
    }
}?>

Ken

#4 ivalea

ivalea
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 09 October 2006 - 06:01 PM

Thanks much Daniel0!  Works great now.  :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users