Jon Lamer
Jon Lamer

Reputation: 428

When a sql result contains multiple rows, how can I fetch each row individually from it?

When I send a query to my SQL database and it returns more than one row, how can I fetch each row individually? I've been failing without any result for hours.

For example:

There is a table, which contains names (fore- and surname):

Hans Hansen
Hans Petersen
Peter Petersen

My query looks like this:

$query = "SELECT * FROM names WHERE forename = 'Hans'";

I tried to use mysql_result(), but this function only returns one field. I thought about creating a second function, which is based on mysql_result() (counting columns -> for Loop to create array), but I made some research and many people say, mysql_result() is very slow, when your result gets bigger.

How can I store the result in different arrays for each row in a fast way to finally create a goodlooking table?

Upvotes: 1

Views: 1087

Answers (2)

botenvouwer
botenvouwer

Reputation: 4432

I don't know what you are using but I guess a mysql database with the old php mysql functions than you use this:

$result = mysql_query("SELECT * FROM names WHERE forename = 'Hans'");

while($row = mysql_fetch_assoc($result)){
    echo "$row[forename] - $row[sirname] - etc. <br>";
}

I also guess you're new to php and did not understand any of this yet but the question you asked is asked multiple times and already answered so try to search and learn before asking this kind of simple questions.

Also you probably asked yourself why declare a variable inside a where loop. The while loop gets the response from mysql_fetch_assoc. When it is false it stops but everytime there is a row it will return an array. Well the array is assigned to the variable $row and does not affect the loop (try not putting $row = and see it still loops). You can then just use the array values and after every spin the mysql result pointer will move one row further. At the last row the function mysql_fetch_assoc will move and see there is no result and it will return false. The loop stops and continues to the next line of php code.

Upvotes: 0

Deepak Rai
Deepak Rai

Reputation: 2203

while($row=mysql_fetch_array($result))
{
    $results[] = $row;
}

Upvotes: 0

Related Questions