Fetching the result array from mysql query in php, while loop issue - php

I have this table in MySql db:
After running this query:
SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC
The result table look like this:
Now in php I try to fetch the result and iterate through the array to determine which group each coach belongs to and get his place in the ranking. Therefore I wrote this:
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
.
.
.
more processing
} // end WHILE
Why $response["scoresGroup"] will always conatins the last value from the result? In this case this is 123. I thought that this is the first iteration through the loop and $response["scoresGroup"] wll hold first element (474), during the second iteration should hold 382 ? What I'm doing wrong here? Do I use correct function to fetch result? or should I use different loop to acheive my goal? Thanks for the help in advance.

You did not post the expected structure of $response; here is what I think you are trying to do:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][] = array(
"scores" => $rowScore["score"],
"count" => $rowScore["count(*)"]
);
}
// $response["scoresGroup"][0]["scores"] = 474
// $response["scoresGroup"][0]["count"] = 1
// $response["scoresGroup"][1]["scores"] = 382
// $response["scoresGroup"][1]["count"] = 1
// $response["scoresGroup"][2]["scores"] = 123
// $response["scoresGroup"][2]["count"] = 1
Or perhaps:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][$rowScore["score"]] = $rowScore["count(*)"]
}
// $response["scoresGroup"][474] = 1
// $response["scoresGroup"][382] = 1
// $response["scoresGroup"][123] = 1

if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score[]["scores"] = $rowScore["score"];
$score[]["count"] = $rowScore["count(*)"];
$numberOfCoaches[] = $score["count"];
$scoresGroup[] = $score["scores"];
$response[]["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM

Looking at the description of your question, you need to define a multidimensional array for storing all the results from query resultset.
Please refer the below code snippet
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"][] = $scoresGroup; //Notice the array here
.
.
.
more processing
} // end WHILE

You are settings $response['scoresGroup'] each time you run the loop, so at the end, it will contain only the last element. Try changing the variable you put the data into on each loop.
$x++;
$response['scoresGroup' . x] = $scoresGroup;

Related

Counting the top checkbox responses when responses are stored as comma separated string in mysql row (Google Form -> mysql)

A form's checkboxes are stored as comma separated values in a single row as a string in mysql. I cannot control this.
When trying to get the top responses, both finding what the responses are, and how many times they appear, I run this:
$query = "SELECT `answer`, COUNT(*) AS CNT FROM `responses` WHERE `answer` <> '' GROUP BY `answer` ORDER BY CNT DESC ";
The individual comma separated values are not counted, rather the combination of them.
Example, 4 people submit checkboxes A and B. 2 only select A, 1 selects A and B, 1 selects B
The result of query above looks like:
A (2)
A,B (1)
B (1)
What I want to achieve is it separating the comma seperated values and yielding:
A (3)
B (2)
I have seen some php explode examples and tried as follows:
if ($result->num_rows > 0) {
while($rows = mysqli_fetch_assoc($result)) {
$ans=explode(',', $rows['answer']);
foreach($ans as $separated) {
echo "<div>".$separated."</div>";
}
}
The result looks like:
a
a
a
b
b
Now how do I store them to count, and then order from most selected to least?
Is my best route to use explode? Or is there another way that is simpler and more logical?
This link explains the issue, and they have a google side fix, but mysql doesn't have the commands: https://support.google.com/docs/thread/54705332?hl=en
Thanks!
###########################################
As answered below, the new code is:
$query = "SELECT `ans_4` FROM `responses` WHERE `ans_4` <> ''";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$ans = [];
while($rows = mysqli_fetch_assoc($result)) {
$ans = array_merge($ans, explode(', ', $rows['answer']));
}
$count = array_count_values($ans);
arsort($count);
foreach ($count as $key => $value) {
echo "<div><span>$key</span><span>$value</span></div>";
}
For PDO:
$stmt = $pdo->query("SELECT ans_4 FROM responses WHERE ans_4 <> ''");
$ans = [];
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC))
{
$ans = array_merge( $ans, explode( ', ', $rows[ 'ans_4' ] ) );
}
$count = array_count_values( $ans );
arsort( $count );
echo( "Largest Concerns" );
foreach ( $count as $key => $value ) {
echo "<div><span>$key</span><span>$value</span></div>";
}
Obviously this is not the best way to store them, and I'm not sure if you can do it in the query. But you probably want to just select that column:
SELECT `answer` FROM `responses` WHERE `answer` <> ''
Then explode and add to a flat array and count the values:
$ans = [];
while($rows = mysqli_fetch_assoc($result)) {
$ans = array_merge($ans, explode(',', $rows['answer']));
}
$count = array_count_values($ans);
The $count array should then yield something like:
Array
(
[A] => 3
[B] => 2
)
Then if needed to sort descending:
arsort($count);

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.
I want to get the records based on these two id number. But this below code returns the output repeatedly.
How do I properly put the while loop code inside a foreach?
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',' ',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array.
$res = mysql_query($sql)
should be on it's own line before the while loop, and then
while($r = msql_fetch_array($res))
This will properly increment through the $res list.
Try this and you are done
As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',',',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}

echo all and entire MySQL Query rows in php without specifically naming each column

I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}

retrieving values into an array

I'm trying to enter all the course_code that have a score < 40 into array and echo it out somewhere. The print_r($carry_over) returns nothing!
$carry_over = array();
while ($row8 = mysql_fetch_assoc($query8)) {
if ($row8['score'] < 40) {
$carry_over[] = array('m.course_code' =>$row8['course_code']);
}
}
print_r($carry_over);
$query8 = mysql_query("SELECT m.score , m.course_code FROM maintable AS m
INNER JOIN students AS s ON m.matric_no = s.matric_no
INNER JOIN courses AS c ON m.course_code = c.course_code
WHERE m.matric_no = '".$matric_no."'
AND m.level = '".$level."'
AND m.score < 40"
) or die (mysql_error());
Your $query8 variable (the database query) should be defined before the while() function. Right now, the while() function iterates over 0 rows which, of course, results in an empty array.
$carry_over = array();
while ($row8 = mysql_fetch_array($query8))
{
$carry_over[] = $row8['course_code'];
}
Since you already check for rows where the score is less than 40 in your SELECT query, the check inside the while() function is redundant. You also missed a single-quote in front of course_code (it was previously a dot), and finally; adding an array inside the $carry_over array is unnecessary when you can just add the value directly to the first array.
2nd UPDATE
$matric_no = MAKE_SURE_TO_DEFINE_THIS;
$level = MAKE_SURE_TO_DEFINE_THIS;
// Fetch rows
$query8 = mysql_query("SELECT maintable.score, maintable.course_code, maintable.matric_no, maintable.level, students.matric_no, courses.course_code FROM maintable, students, courses WHERE (maintable.matric_no = '" . $matric_no . "' AND maintable.matric_no = students.matric_no) AND (maintable.course_code = courses.course_code) AND (maintable.level = '" . $level . "')");
$carry_over = array();
while ($row8 = mysql_fetch_array($query8))
{
// Save data to array
$carry_over[] = $row8['course_code'];
}
echo 'We found ' . mysql_num_rows($query8) . ' rows';
print_r($carry_over); // DEBUG
The array loop should be
If($row8['score'] < 40)
$carry_over[] = $row8['course_code'];
I think you might have to debug $row8 array first. to see what is inside or it probably got nothing at all

Categories