Adding to a loop in PHP without overwriting - php

I am trying to store the dates and month name from my database in this format. I am aiming to store the month and then count the entries in that month and then store the count. This is my loop, but I have trouble formatting the array properly.
while ( $row = mysql_fetch_assoc($res) ) {
if ($row['Date'] != $prev_date) {
$values=array(
$row['Date'] => $count,
);
$prev_date = $row['Date'];
}
$count++;
}
print_f($values);
You can see that I will always overwrite my previous array and I am not really adding entries into the array. I couldn't figure out how to do it. I'm basically trying to see the number of entries per month.
OLD Update: Currently learning the MYSQL thing that one commenter mentioned. I'll update when I get it.

You can make this using group by in sql, some like this: select date, count(*) from table group by date
Edit:
If you need only count by month use some like this: select MONTH(dateField) as NewDate, count(*) FROM table GROUP BY NewDate

I almost got it!
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
if ($row['Date'] != $prev_date) {
$values[$row['Date']] = $count;
$prev_date = $row['Date'];
$count = 0;
}
$count++;
}
Update: Need a little help with this part.
My output:
Array ( [9] => [10] => 999 [11] => 986 )
999 was supposed to be stored in 9 and 986 was supposed to be stored in 10.
Update: Here's my new code, I would appreciate it if someone can show me a more efficient way.
$sql = "SELECT MONTH(AddDate) AS Date, column_name FROM table ORDER BY AddDate ASC";
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
if ( $row['Date'] != $prev_date) {
$month = $row['Date'];
$sql = "SELECT count(MONTH(AddDate)) AS EntryAmount FROM `table` WHERE MONTH(AddDate)=$month ";
$countResults = mysql_query($sql) or die(mysql_error());
if( $entryAmount = mysql_fetch_array($countResults) ) {
$values[$row['Date']] = $entryAmount['EntryAmount'];
}
$prev_date = $row['Date'];
}
}
Output:
Array ( [9] => 999 [10] => 986 [11] => 264 )

Not sure I understand what you're trying to do. How about this?
$values[$row['Date']]++;

How about looping on the result of a query something like this:
SELECT COUNT(MONTH(AddDate)) AS EntryAmount, MONTH(AddDate) as MonthValue FROM table GROUP BY MONTH(AddDate)

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);

Values of keys in different arrays

So I have a query that returns the following results in PHP, and I'm trying to add the total of the hours_played, I have tried array_sum() but that does not seem to work, I would like to be able to add the values of hours_played to be 11 that way I can then pass that it another function :
Array
(
[id] => 1
[team_id] => 1
[hours_played] => 1
)
Array
(
[id] => 2
[team_id] => 1
[hours_played] => 4
)
Array
(
[id] => 3
[team_id] => 1
[hours_played] => 6
)
I'm a little bit lost and do I need to store the able Arrays in another array to be able to do this? The results above are from a sql query and is what is printed on the page when I print_r the $row variable.
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
print_r($row);
}
You can either sum all the columns hours_played after having fetched the results and assigned them into an array, as shown below
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($res)){
$result[] = $row;
}
$sum = array_sum(array_column($result, "hours_played"));
echo $sum;
..or you can sum it up as you loop the results.
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$sum = 0;
while($row = mysql_fetch_assoc($res)){
$sum += $row['hours_played'];
}
echo $sum;
Or, if you just need the total hours played, you can do that directly in one query, using COUNT() in MySQL.
$sql = "SELECT SUM(hours_played) as sum_hours_played FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
echo $row['sum_hours_played'];
PHP array_column()
PHP array_sum()
MySQL COUNT()
WARNING
Do not use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
See the red box?
Learn about prepared statements instead, and use PDO or MySQLi
- this article can help you decide which.
You're really close . You just need to add the 3rd index of each array together:
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$total = 0;
while($row = mysql_fetch_assoc($res)){
$total += $row['hours_played'];
}
CONVERSELY You can use the numbered index as well.
$total = 0;
while($row = mysql_fetch_assoc($res)){
$total += $row[2]; // indexes start at 0
}
echo $total; // Will print 11 if your arrays you posted are correct.
IN ADDITION --- WARNING!! You need to be using mysqli instead of the far less secure and now deprecated mysql
Most Important
Avoid using mysql_* functions. They are no longer maintained and are also officially deprecated.
Read about using prepared statements instead, and change your existing code to use PDO or MySQLi
You can get a total of hours_played in the while loop. Try this:
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$total_hours_played = 0; // initialize a variable to get sum of hours
while($row = mysql_fetch_assoc($res)){
$total_hours_played += $row['hours_played'];
}
echo $total_hours_played;
$sum = array_sum(array_column($array, 'hours_played'));

How to fetch and display primary key of an array that fetch from database in php

My query is like this:-
date = date('Y-m-d');
$ddate = date('Y-m',strtotime($date) + (24*3600*$add_days));
$result=mysql_query("SELECT id, end_date, lid, date_format(tbl_ldet.`start_date`, '%Y-%m') FROM tbl_ldet WHERE lid='".$id."'");
while($row = mysql_fetch_array($result))
{
$result_array[] = $row[3];
}
$people = $result_array;
if (in_array($ddate, $people))
{
//echo '<pre>'; print_r($people); echo '</pre>';
$dcount++;
}
I got an array like this, which is fetched from database according to the above query,
Array
(
[0] => 2017-12
[1] => 2018-01
[2] => 2018-02
)
The problem is, how can i able to fetch and display the primary key of the "tbl_ldet" from the array which i got
Thanks in advance

ARRAY PHP How to put variables in array

Hi guys i would like to ask help on my problem..
I have 4 variables made from my query:
$sql1 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Online Transaction' "));
$sql2 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Walkin Transaction' "));
$sql3 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Online Transaction' "));
$sql4 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Walkin Transaction' "));
I would like to put them in an array..to be exactly on my expectations.
Here is my sample code:
$stack = array($sql1, $sql2);
array_push($stack, $sql3, $sql4);
$query = print_r($stack);
$result = $query;
print json_encode($result);
It display like this on my browser:
Array ( [0] => 0 [1] => 8 [2] => 0 [3] => 1 ) true
But i want to display it like this:
[{"0","1"},
{"2","3"}]
I am planning to make a line graph on this.. I have a Chart.min.js and jquery.min.js
If any way.. The whole point.. i want to make a line graph that would compare my data from current year to last year.
Help me pls. :(
Give a try
<?php
$a = array(0,8,0,1) ;
echo "<pre>";print_r(json_encode(array_chunk($a, 2)));
?>
with that. You can get this result
[[0,8],[0,1]]
Btw, Why you need to do that with your array ? .
Edited
After i check your question again, So you want get the order
<?php
$stack = array(0,8,0,1) ;
$array2= array();
foreach ($stack as $key => $val) {
$array2[] = $key;
}
echo "<pre>";print_r(json_encode(array_chunk($array2, 2)));
?>

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

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;

Categories