Extraction data from MySQL table using PHP
Get the solution ↓↓↓i'm trying to extract data from mysql. I have some query looking like thisSELECT 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
Answer
Solution:
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.
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the requested url was not found on this server. xampp
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.