Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Shortest code for mysql rows iteration 1

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR
Here is the piece of code I use when I need to loop through several mysql rows (I use arrays just in case I have to do an improbable nested query) :

Code:
$sql_query[1] = "SELECT ____ ";
$sql_query[1] .= "FROM ____ ";
$sql_query[1] .= "WHERE ____ ";
$sql_query[1] .= "AND ____ ";
$sql_query[1] .= "GROUP BY ____ ";
$sql_query[1] .= "ORDER BY ____ ";
$sql_query[1] .= "ASC";

$sql_result[1] = mysql_query($sql_query[1],$db_connect);
$sql_num[1] = mysql_num_rows($sql_result[1]);

    if($sql_num[1] > 0) {
    
    $cur[1] = 1;
        
    		while ($sql_num[1] >= $cur[1]) {
    		
    		$row = mysql_fetch_array($sql_result[1]);
    		
    		$____ = $row["____"];  		
    		
    		echo"
    		" . $____ . "<br />
    		";
    		
    		$cur[1]++;
    		}
    
    }

So, my question is : is there a way to do the same thing with less code?

Thanks.
 
Sure.

Since PHP's mysql_fetch_*() functions all return FALSE when there is no more data in a result set your code can drop the mysql_num_rows() call and while-loop on the mysql_fetch_array() call.

Also, quit assigning values from the result set to variables and just reference the result set array.

Code:
$sql_query[1] = "SELECT ____ ";
$sql_query[1] .= "FROM ____ ";
$sql_query[1] .= "WHERE ____ ";
$sql_query[1] .= "AND ____ ";
$sql_query[1] .= "GROUP BY ____ ";
$sql_query[1] .= "ORDER BY ____ ";
$sql_query[1] .= "ASC";

$sql_result[1] = mysql_query($sql_query[1],$db_connect);

while ($row = mysql_fetch_array($sql_result[1])
{
            echo"
            " . $row["____"] . "<br />
            ";
}



Want the best answers? Ask the best questions!

TANSTAAFL!!
 

Wow .. that's clean and beautiful ;)

Thanks for that!

I see you're still a very active member on this site.
BTW, what's your projects for the coming year?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top