0

I wanted to get all the rows in a given column and output them, but my code is just not working:

$result = mysql_query("SELECT Name,Number FROM Users WHERE Customer_ID = 1);
  if (!$result) {
    die("Query to show fields from table failed");
  }
$row = mysql_fetch_assoc($result);

echo $row['Name'];
echo $row['Number'];

^ This code is only displaying the first row, how can I list all the rows? 
1
  • 3
    You are missing a " at the end of the first line for starters. Commented Sep 4, 2011 at 15:35

2 Answers 2

3

You have to loop through the rows. Getting the mysql_fetch_assoc 1 time, will only return you 1 row (the first one), so you have to do a mysql_fetch_assoc for each row in the result. Something like this would do:

while($row = mysql_fetch_assoc($result))
    echo $row['Name']." ".$row['Number'];
Sign up to request clarification or add additional context in comments.

3 Comments

It worked, however, it's outputting the same data multiple times, although it's stored only in one row
then please check your query, maybe run it in phpmyadmin or mysql, to see what exactly it returns. the above code should work perfectly if the query is correct.
I'm sorry. It was from my SQL statment. Thank you!
0

In order to display all the rows, you need to use 'while' loop as following:

while($row = mysql_fetch_assoc($result)){

    echo $row['Name'];
    echo $row['Number'];
    echo '<br />';
}

Hope this helps.

3 Comments

This helps too. Thanks. Is it possible to tell PHP to fetch identical rows only once? For example, I'm getting 50 'Number: 12345678'.
Maybe add a GROUP BY Number statement to the end of you MySQL query would help.
You can achieve this by using the keyword 'Distinct' in your query. This will make sure that all the records are unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.