Fetching a row

It was important to show how you can fetch a single cell of data from MySQL, but now let’s look at a much more efficient method. So, replace the for loop of query.php with the new loop in following Example, and you will find that you get exactly the same result that was displayed.

for ($j = 0 ; $j < $rows ; ++$j)
	$row = mysql_fetch_row($result);
	echo 'Author: ' . $row[0] . '<br />';
	echo 'Title: ' . $row[1] . '<br />';
	echo 'Category: ' . $row[2] . '<br />';
	echo 'Year: ' . $row[3] . '<br />';
	echo 'ISBN: ' . $row[4] . '<br /><br />';

In this modified code, only one-fifth of the calls are made to a MySQL-calling function (a full 80 percent less), because each row is fetched in its entirety using the mysql_fetch_row function. This returns a single row of data in an array, which is then assigned to the variable $row.
All that’s necessary then is to reference each element of the array $row in turn (starting at an offset of zero). Therefore $row[0] contains the Author data, $row[1] the Title, and so on, because each column is placed in the array in the order in which it appears in the MySQL table. Also, by using mysql_fetch_row instead of mysql_result, you use substantially less PHP code and achieve much faster execution time, due to simply referencing each item of data by offset rather than by name.


You may also like...