most efficient way of checking for mysql results...

Discussion in 'PHP' started by tarponkeith, Dec 9, 2007.

  1. #1
    Hey PHP Gurus...

    I've been using code like this:
    		if ($db_row = @mysql_fetch_assoc($db_data))
    		{
    			if (!$db_row = @mysql_fetch_row($db_data)) { unset($zdbconn); unset($db_data); unset($db_row); return false; }
    			$first_field = $db_row[0];
    		}
    
    PHP:
    to check if a query returns any results, and in this example, save the first field to a variable... Just wondering if there's a more efficient way of checking for results and saving information...

    Thanks :)
     
    tarponkeith, Dec 9, 2007 IP
  2. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #2
    
    while ($db_row = mysql_fetch_array($db_data, MYSQL_NUM)) {
    	if ($db_row[0]) $first_field = $db_row[0]; else continue;
    }
    
    PHP:
    Always use a while loop when handling mysql related.
     
    Kaizoku, Dec 9, 2007 IP
    tarponkeith likes this.
  3. tonybogs

    tonybogs Peon

    Messages:
    462
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    if (mysql_num_rows($queryResult) > 0)
    {
        // do something
    }
    
    PHP:
    The way you have done it will force 2 fetches when you dont need to.

    Hope this helps :)
     
    tonybogs, Dec 9, 2007 IP