Forum Moderators: open

Message Too Old, No Replies

How to handle an empty field set during fetch array?

While loop just skips any if functions and moves on to the next.. :(

         

thekid

12:06 am on Nov 3, 2006 (gmt 0)

10+ Year Member



Heya,

Hope someone can help me out here.

I have abunch of code that is pulling information from a COMPANY table. One of the entires for a COMPANY is CONTACTCODE.

Im using a while loop to extract the Company Name, Contact Code, and Phone number to be displayed in an HTML table.

with in the while loop, I have the code below to hand another while loop. The idea is to use the CONTACT CODE extracted from the COMPANY table to loop through and fetch the First and Last name.

It works alright if the CONTACT CODE from the COMPANY table matches and entry in the CONTACT table.

The problem is when the CONTACT CODE can't be found in the CONTACT table.

what I would like to do is catch and display that there is no matching record. It seems to me though that when fetch_array finds no field it simply does the loop again and I can't seem to trap it with any isset() or empty() functions.

$contactcode = $row['MAINCONTACT'];
$query2 = 'SELECT * FROM CONTACT WHERE CONTACTCODE = "'.$contactcode.'"';
$result2 = mysql_query($query2) or die(mysql_error());
while($row2 = mysql_fetch_array($result2)){

echo '<td width="250" height="35" align="center">'.$row2['FIRSTNAME'].'&nbsp;'.$row2['LASTNAME'].'';
}
echo '<td width="250" height="35" align="center">'.$row['MAINPHONE'].'</td>';
echo '</tr>';

Any ideas? Need a better explaination?

Thanks!

Mike

thekid

12:18 am on Nov 3, 2006 (gmt 0)

10+ Year Member



FIgured it out....

Used an if statement with mysql_num_rows applied to my resultto control what happens if there is no rows returned on that pass

Took awhile there...this stuff is PICKY.

coopster

4:16 pm on Nov 7, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, thekid.

Another option here would be to JOIN the tables together and run a single query. If you use a LEFT JOIN, any contacts missing in your right hand table would return NULL values.

Some examples and explanations:
LEFT JOIN versus INNER JOIN [webmasterworld.com]
MySQL and Joins [webmasterworld.com]
Help needed on Joins [webmasterworld.com]
List row values from different tables [webmasterworld.com]
An example discussion JOIN in general:
SELECT within SELECT [webmasterworld.com]