Jump to content

[SOLVED] How to test if query returned anything?


deko

Recommended Posts

Here's the code in question:

<?php
$var = trim($_GET['var']);
$cnx = mysql_connect('localhost','user','paswd');
$db = mysql_select_db('database_1');
if ($cnx && $db)
{
$sql = "SELECT something where var = ".$var;";
$result = mysql_query($sql);  
while ($foo = mysql_fetch_array($result))
{
    [do stuff with data]
        }
// now get stuff from database_2
         if (@mysql_select_db('database_2'))
{
	$sql = "SELECT something else based on $var_id;"
	$result = mysql_query($sql); 
	while ($bar = mysql_fetch_array($result))
                {
                    [do stuff with data]
                 }
         }

Two questions:

 

1) How do I test $result (or mysql_fetch_array($result)) before I get into the while loop?

 

2) Is it okay to switch databases like this?  I assume I DON'T need to mysql_close; here... just mysql_select_db to use another database--is this correct?

 

thanks.

 

EDIT: please make use of

 tags

Hey,

 

I'm kind of a noob too. but one thing i noticed is that you dont count the number of results that match your search criteria.

 

1.

for eg your code may be as follows.

$sql = "SELECT something FROM TABLENAME where var = ".$var;";
$result = mysql_query($sql); 

$num=mysql_num_rows($result);
echo $num; \\*1

while($row = mysql_fetch_array($result))
{
echo $row['something']; \\*2
}

at *1 : it will display the number of records that matched with your search criteria.

at *2 : it will display the field value which matches with your search criteria. This will happen until php loops through all the matched records.

 

hope this helps.

 

2. Im sorry I dont know much bout switchin database. I always use one database for one project.

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.