2

i'm trying to extract data from mysql. I have some query looking like this SELECT q1, COUNT(*) FROM results GROUP BY q1 and as result I'm expecting something like this:

q1  COUNT(*)
0   7
1   1
2   4
3   1

It works in phpMyAdmin workflow, but if I try to repeat this query from my pagename.php file I'm failed.

$q1_ans = mysqli_query($link, "SELECT q1, COUNT(*) FROM results GROUP BY q1");
$q1_arr = mysqli_fetch_assoc($q1_ans);
foreach($q1_arr as $key => $value) {
        echo "<br>$key is at $value";
      }

And as result I have

q1 is at 0 COUNT(*) is at 7

How can I get array looking like this??

0 is at 7
1 is at 1
2 is at 4
3 is at 1
0

2 Answers 2

3

You can do it directly in the query :

"SELECT CONCAT(q1,' is at ',COUNT(*)) as YourName
 FROM results GROUP BY q1"

This will return them as one field.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your contribution
1

mysqli_fetch_assoc() fetches ONE row from the database. You have to repeat it until there is no more data:

$q1_ans = mysqli_query($link, "SELECT q1, COUNT(*) FROM results GROUP BY q1");
while ($q1_arr = mysqli_fetch_assoc($q1_ans)) {
    foreach($q1_arr as $key => $value) {
        echo "<br>$key is at $value";
    }
}

This fixes the issue that you only get one result. To fix your output, see @sagi's answer.

1 Comment

thank you for your help, getting only first row was my big trouble

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.