Please help me in php mysq to count data by group - php

I have a table clicks like this
+-----+-----+-------+-------+
| id | time | site |
+-----+-----+-------+-------+
| 1 | 8 4 2013 | site1 |
| 2 | 8 4 2013 | site1 |
| 3 | 9 4 2013 | site2 |
| 4 | 6 4 2013 | site1 |
+-----+-----+------+--------+
I want to show result like this
Date | Count
8 4 2013 | 2 click
6 4 2013 | 1 click
i have this code
$id = 'site1';
$getclk = mysql_query("SELECT * FROM clicks WHERE site='$id'");
$clk = mysql_num_rows($getclk);
print $clk;
this code show only count of rows and i want to show count of row grouped by time.
GROUP BY command works for this but i don't know how to do this.
please help me i dont know how to do this, please give me full code to do this.

I think it should be:
SELECT COUNT (id) as countClicks, time as Date
FROM clicks
[WHERE site = ?]
GROUP BY time
ORDER BY countClicks DESC
Also, you shouldn't use mysql_* functions because they are deprecated.

$getclk="SELECT date,count(*) as c FROM Clicks WHERE site='$id' GROUP BY date ORDER BY c DESC";
Then loop through the results and display them. please give me full code to do this. So Sorry, not the right forum for that

SELECT time, COUNT(*) as count FROM clicks GROUP BY time

This should give you result in the format you've asked for:
$getclk = mysql_query("select time as Date, concat(count(*), ' click') as Count
from Clicks
where site = '$id'
group by time
order by Count desc");
Please note the use of mysql function concat() function to append click text to number of records grouped by time under Count column would be better if you appended this text in php instead of mysql so that less data would be transferred from the database server.
As already made aware by other answerers, mysql_ functions are deprecated, you should be using either mysqli or pdo for new code.

write Your query like below
$id = 'site1';
$getclk = mysql_query("SELECT count(id) as clcount,time FROM clicks WHERE site='$id' group by time order by time");
$clk = mysql_num_rows($getclk);
print_r($clk);

Related

Get multiple SQL rows with similar column value

I'm making a cron job where it publishes (inserting new into the database) an article. I was able to pull it through but there is one query I can't get to work. I'd like to print certain rows from another table that can be inserted to the article being published. Supposed I have this another table like this:
+----------+-------------+
| filename | released |
+----------+-------------+
| tigers | 2020-05-27 |
| wolves | 2020-05-27 |
| earth | 2020-05-27 |
| bamboo | 2020-05-27 |
| glaciers | 2020-05-02 |
+----------+-------------+
How can I print the result of the filenames as:
bamboo, earth, tigers, wolves
so that the cron can insert it to the article table's specified column with the same format? I've tried using this query below but it only returns one result, which is the tigers filename.
SELECT filename,
GROUP_CONCAT(filename ORDER BY filename ASC SEPARATOR ', ')
FROM table
WHERE released='2020-05-27'
GROUP BY released
Many thanks for the help in advance!
Using TheImpaler's query, I managed to solve what I'm trying to get with the following code:
$get = $database->query("SELECT released,
GROUP_CONCAT(filename ORDER BY filename ASC SEPARATOR ', ')
FROM another
WHERE released='2020-05-27'
GROUP BY released");
$row = mysqli_fetch_array($get);
echo $row['1']; // Prints the comma-separated result of the filenames
echo print_r($row); // Prints the entire row
Many thanks for the comments, it gave me an idea and had my query validated!

How to user order by clause to get records correctly with data in shape of 01/2020

Hi I have some file's records with the number like 01/2020, 02/2020 up to so on and I have used order by clause to get the records in order by these numbers but it return correctly from 01/2020 to 10/2020 then it show me 100/2020 is there a solution? kindly share with me.
If my assumption is correct whereby the format of this record is running_no/year then you need to extract the year to include in order by. Consider example below.
If data is like this:
+----------+
| Value |
+----------+
| 01/2020 |
| 02/2020 |
| 10/2020 |
| 100/2020 |
| 01/2021 |
| 10/2021 |
+----------+
Whereby the 4 digits at the back represent running year, then you can extract the year from if in a few ways. Here I'm showing two example using RIGHT() and SUBSTRING_INDEX().
example 1:
SELECT * FROM table ORDER BY RIGHT(Value,4) ASC, ABS(Value) ASC;
example 2:
SELECT * FROM table ORDER BY SUBSTRING_INDEX(Value,'/',-1) ASC, SUBSTRING_INDEX(Value,'/',1) ASC;
There are more ways to achieve this as long as you can be certain it will return the result the way you want.
My problem has been solved by using ORDER BY ABS(MyField)

Create API endpoint for fetching dynamic data based on time

I have a scraper which periodically scrapes articles from news sites and stores them in a database [MYSQL].
The way the scraping works is that the oldest articles are scraped first and then i move onto much more recent articles.
For example an article that was written on the 1st of Jan would be scraped first and given an ID 1 and an article that was scraped on the 2nd of Jan would have an ID 2.
So the recent articles would have a higher id as compared to older articles.
There are multiple scrapers running at the same time.
Now i need an endpoint which i can query based on timestamp of the articles and i also have a limit of 10 articles on each fetch.
The problem arises for example when there are 20 articles which were posted with a timestamp of 1499241705 and when i query the endpoint with a timestamp of 1499241705 a check is made to give me all articles that is >=1499241705 in which case i would always get the same 10 articles each time,changing the condition to a > would mean i skip out on the articles from 11-20. Adding another where clause to check on id is unsuccessful because articles may not always be inserted in the correct date order as the scraper is running concurrently.
Is there a way i can query this end point so i can always get consistent data from it with the latest articles coming first and then the older articles.
EDIT:
+-----------------------+
| id | unix_timestamp |
+-----------------------+
| 1 | 1000 |
| 2 | 1001 |
| 3 | 1002 |
| 4 | 1003 |
| 11 | 1000 |
| 12 | 1001 |
| 13 | 1002 |
| 14 | 1003 |
+-----------------------+
The last timestamp and ID is being sent through the WHERE clause.
E.g.
$this->db->where('unix_timestamp <=', $timestamp);
$this->db->where('id <', $offset);
$this->db->order_by('unix_timestamp ', 'DESC');
$this->db->order_by('id', 'DESC');
On querying with a timestamp of 1003, ids 14 and 4 are fetched. But then during the next call, id 4 would be the offset thereby not fetching id 13 and only fetching id 3 the next time around.So data would be missing .
Two parts: timestamp and id.
WHERE timestamp <= $ts_leftoff
AND ( timestamp < $ts_leftoff
OR id <= $id_leftoff )
ORDER BY (timestamp DESC, id DESC)
So, assuming id is unique, it won't matter if lots of rows have the same timestamp, the order is fully deterministic.
There is a syntax for this, but unfortunately it is not well optimized:
WHERE (timestamp, id) <= ($ts_leftoff, $id_leftoff)
So, I advise against using it.
More on the concept of "left off": http://mysql.rjweb.org/doc.php/pagination

PHP MYSQL Detect if new row is added

Any Idea how can I identify if there is new client added on my database.
I was thinking about identifying it thru date_added field.
id client_name date_added
---------------------------------
1 ABC 2013-01-02
2 XYZ 2013-01-03
3 EFG 2013-01-02
4 HIJ 2013-01-05
as you can see a new client added HIJ on 2013-01-05.
I was looking with this kind of result:
Client List
Total NO: 4
New Client
Total No: 1
Client Name: HIJ
add a field new to the table, default it to 1, on page load use that for the select and set it to 0 to indicate its not longer new.
It's hard to tell but based on your comment ...my reference date is 1 month interval... you might be looking for something like this
SELECT id, client_name, new_count, total_count
FROM
(
SELECT id, client_name
FROM clients
WHERE date_added BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
) c CROSS JOIN
(
SELECT
(
SELECT COUNT(*) new_count
FROM clients
WHERE date_added BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
) new_count,
(
SELECT COUNT(*) total_count
FROM clients
) total_count
) t
Obviously you can easily change CURDATE() with any other reference date in the past in this query and you get results for that date.
Lets assume that you have following sample data
+------+-------------+------------+
| id | client_name | date_added |
+------+-------------+------------+
| 1 | ABC | 2013-05-13 |
| 2 | XYZ | 2013-06-13 |
| 3 | EFG | 2013-06-13 |
| 4 | HIJ | 2013-08-11 |
+------+-------------+------------+
and today is 2013-08-13 then the output from the query will be
+------+-------------+-----------+-------------+
| id | client_name | new_count | total_count |
+------+-------------+-----------+-------------+
| 4 | HIJ | 1 | 4 |
+------+-------------+-----------+-------------+
You could remember, in your webpage or PHP script, the highest ID value previously seen. Or the highest timestamp (better than a date) previously seen.
I prefer ID or Version numbers for concurrency-related stuff (locking, finding the latest etc) -- since they should be defined to be ascending, can't suffer "same millisecond" collisions, and are more efficient.
I assume you're going to hold the "state" of your application (as to what the user has seen) in hidden fields in the form, or somesuch. This would then track the "last seen" and allow you to identify "newly added" since the last pageview.
If you expect to identify newly added when coming from a different page or logging onto the application, you'll need to store the "state" in the database instead.
That depends on what you consider NEW. You have to define what you're going to compare the records against (reference date). Once you define it, you could use a query like the following:
SELECT * FROM client WHERE date_added >= '$date'
where $date is the reference date.

Get all unique numbers in MySQL table using php

I am trying to build an archive list for a blog using php and mysql. The problem is I am not sure of the best way to do this.
I was hoping there was a way to get a list of years and than display them so lets say my table has id | year | content and has the current rows
1 | 2013 | content
2 | 2013 | content
3 | 2013 | content
4 | 2012 | content
5 | 2012 | content
6 | 2011 | content
is it possible to make a mysql statement that well only return IDs 1,4,6, if so how?
try this
select * from table
group by year
if you consider the order then add this in the end order by id
DEMO here
you can also get the specified Id by using Min or Max. like this
select min(id) ,year ,content from table
group by year
demo
select min(id) , year from table group by year
To just get a list of the 'year's in your table:
select distinct year from table
Depending on the size of your table and how often you're running the query, you could think about indexing on 'year'.

Categories