Query MySQL count data & turn into JSON - php

My table contains a column of 'datetimes', with an id.
+----+---------------------+
| id | datetime |
+----+---------------------+
| 0 | 2016-09-02 12:13:13 |
| 1 | 2016-09-02 10:16:11 |
| 2 | 2016-09-05 11:03:23 |
| 3 | 2016-09-08 11:34:45 |
| 4 | 2016-09-08 09:23:06 |
| 5 | 2016-09-08 10:22:05 |
| .. | ... |
+----+---------------------+
There will be multiple instances of each date in the table. My aim is to gather the amount of times each date occurs. So for the table above:
2016-09-02 => 2
2016-09-05 => 1
2016-09-08 => 3
I then need to move the data into JSON format using PHP like so:
[{"date":"2016-09-02","count":"2"},
{"date":"2016-09-05","count":"1"},
{"date":"2016-09-08","count":"3"}]
The JSON format will be used by a d3.js script I have written to plot each date against the frequency each date occurs.
I have never dealt with this kind of query before so I really have no idea where to start, or how to use PHP to move into JSON format. Thank you to anyone that can help.

Use the following query:
SELECT DATE_FORMAT(datetime, '%Y-%m-%d') AS `date`,
COUNT(*) AS `count`
FROM yourTable
GROUP BY DATE_FORMAT(datetime, '%Y-%m-%d')
Then create the JSON in your PHP code:
$a = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$a[] = array('date' => "$row['date']", 'count' => "$row['count']");
}
$json = json_encode($a);

I think below SQL useful to you. please run and see
SELECT DATE_FORMAT(datetime, '%Y-%m-%d'),count(*)
FROM yourTable
GROUP BY 1
order by 1

Related

Finding overlapping times from a select statement

Okay, so I have a table (timetable) in a database (calendar) which if formatted like so:
+----+--------+-----------+-----------+---------+
| id | name | day | startTime | endTime |
+----+--------+-----------+-----------+---------+
| 1 | George | Sunday | 12:00 | 14:00 |
| 2 | Dan | Monday | 13:30 | 15:30 |
| 3 | Jeff | Wednesday | 12:00 | 14:00 |
| 4 | Bill | Monday | 13:45 | 15:45 |
+----+--------+-----------+-----------+---------+
Then I have some PHP as follows:
<?php
$sql = "SELECT * FROM timetable WHERE id IN (1, 2, 3, 4)"
$result = $con->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
$array2[] = $row;
}
echo json_encode($array2, JSON_PRETTY_PRINT);
?>
And that outputs the entire table, as an associated array in JSON format.
I want it to only output the two that clash. There will never be more than two that clash in the database due to the input method, so it only needs to check if there's one clash, and output the JSON for both rows.
I'm not sure where to start. Is it better to do it programatically via PHP, or is there a way to do with with mysql? I was thinking if it's done programatically, maybe two nested for loops and if statements for greater than or less than on the time fields? But seems messy, and I'm thinking there's likely a more clever end elegant solution that I can't think of.
Thank you for any help you can provide.
You can do it with JOIN in SQL like below:-
To find "any overlap", you compare the opposite ends of the timeframe with each other.
SELECT * FROM timetable a
JOIN timetable b
on a.starttime <= b.endtime
and a.endtime >= b.starttime
and a.name != b.name;

How to count record month group with unix timestamp in php & mysql.

Example my_table
ID | Name | Date
--------------------------
12 | John | 123456789
13 | Mike | 987654321
...
29 | Rick | 123498765
30 | Adam | 987651234
show output result like this
Month | Count
--------------------------
3 | 5 |
6 | 8 |
How can I do this with PHP?
You can do this using MySQL Query as below.
SELECT MONTH(FROM_UNIXTIME(`Date`)) `Month`
,COUNT(ID)
FROM my_table
GROUP BY `Month`;
Since post tagged codeigniter
This is codeigniter way:
$query = $this->db->select("month(from_unixtime(`Date`)) as `month`, count(1) as `count`",FALSE)
->group_by("month");
->get("your_table");

MySql AVG() and WHERE

I'm struggling on how to write this query and cant quite find an answer to help me with my case.
Consider the following table:
-----------------------------------------------
| ID | Value1 | Value2 | Value3 | Date |
-----------------------------------------------
| 1 | 10 | 23 | 30 | 2015-01-01 |
-----------------------------------------------
| 1 | 11 | 33 | 40 | 2015-02-01 |
-----------------------------------------------
| 2 | 26 | 93 | 20 | 2015-01-01 |
-----------------------------------------------
| 2 | 11 | 33 | 50 | 2015-02-01 |
-----------------------------------------------
I want to retrieve the average value of Value1 where the Date is 2015-01-01
I thought that
SELECT AVG(PAM_1) FROM MyTable WHERE DATE = 2015-01-01
would work but of course it does not. I'm aware that I probably need to use HAVING but I'm being confused if I must also use GROUP BY and if do I need the AS (something) part.
EDIT
The problem was not related to the query. I was supplying the date trough a variable as such:
$sth = $db->prepare("SELECT AVG(Value1) FROM MyTable WHERE DATE = $date");
Which is not possible to do with prepared statements.
Your query is basically fine. Your date constant is not. Dates constants should be enclosed in single quotes:
SELECT AVG(PAM_1)
FROM MyTable
WHERE DATE = '2015-01-01';
If the date could have a time component, then the following is the best way to handle this:
SELECT AVG(PAM_1)
FROM MyTable
WHERE DATE >= '2015-01-01' AND DATE < '2015-01-02';

Retrieving a particular column value from multiple data rows PHP/MySQL

I trying to put a query together which echo/prints one particular column value from within the table, but within a particular time frame but I'm not having much luck. From the Query below, Im trying to get the '267' in the targets_id=1 row under the targets_set column to echo/print. I get the error message "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource ". How do I get it to echo?
<?php
$dealer = $_SESSION['sp_dealer_code'];
require_once ('/database.php');
$result = mysql_query("SELECT targets_set FROM targets WHERE targets_nmc='F80', sp_dealer_code=$dealer AND `targets_date`
BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 23:59:59' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['targets_set'];
?>
The Database table 'targets' and some sample data
targets_id | sp_dealer_code | targets_nmc | targets_set | targets_actual | targets_date
1 | 1234 | F80 | 267 | 270 | 2014-01-01 01:00:00
2 | 1234 | F8R | 350 | 300 | 2014-02-01 01:00:00
3 | 4567 | F80 | 210 | 200 | 2014-03-01 01:00:00
4 | 4567 | F8R | 267 | 260 | 2014-01-01 01:00:00
Your query is off. WHERE A, B AND C is not valid MySQL; rather, it should be WHERE A AND B AND C:
SELECT targets_set
FROM targets
WHERE
targets_nmc='F80'
AND sp_dealer_code=$dealer
AND `targets_date` BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 23:59:59'
LIMIT 1
When the statement is executed, no result set is given back. That's why you get that error message when you try to fetch the result as an associative array.

select latest element from mysql table

I need to write a query to retrieve values from two columns using mysql table
My table has the following strucutre
| ID | user_id | datetime | message |
| 1 | 21 | 2012-05-10 04:13:01 | message1 |
| 2 | 07 | 2012-05-10 04:17:51 | message2 |
| 3 | 21 | 2012-05-11 04:21:51 | message3 |
| 4 | 21 | 2012-05-11 04:43:51 | message4 |
| 5 | 07 | 2012-05-11 04:21:51 | message5 |
| 5 | 21 | 2012-05-11 04:43:51 | message6 |
i wrote the below query
$query="SELECT MAX(datetime) FROM messages where user_id=21 and date=2012-05-11";
but i am not getting latest record from table iam getting null value
help us
$query="SELECT MAX(datetime) FROM messages where user_id=21 and date LIKE '2012-05-11%'";
You should use DATE(date) to get date of timestamp. MySQL function DATE() extracts only date without hours, minutes and seconds.
Here is your query:
SELECT MAX(datetime)
FROM messages
WHERE user_id = 21 AND DATE(date) = '2012-05-11'
Have you tried the following?
$query="SELECT MAX(datetime) FROM messages where user_id=21";
Update:
In your question, you didn't specify if you wanted to retrieve last record for a certain date. If you do, you'd need to use MySQL's date function.
Are you looking for the most recent record? You can get this with a subquery:
$query = "SELECT * FROM messages WHERE datetime = (SELECT MAX(datetime) FROM messages)";
Your query asks for ".....date=2012-05-11";" but your table does not have the field named date? did you mean datetime? if so, you may want to try ".....datetime like '2012-05-11%'";

Categories