get statistic data from two tables - php

two tables - posts - and users, common column - posts.user/users.id
I need to output some statistic data, i.e. how much posts each user has for today, last 7-30-365 days and total count.
The code below works, but I'm interesting to reduce number of queries, if possible.
$stmt0 = $db->query("select * from users where role = 'mod' order by name asc");
$count0 = $stmt0->rowCount();
while($row0 = $stmt0->fetch()){
$stmt1 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) = date(now())");
$stmt2 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 7 day");
$stmt3 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 30 day");
$stmt4 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 365 day");
$stmt5 = $db->query("select id from posts where user = " . $row0['id']);
}
$count1 = $stmt1->rowCount();
$count2 = $stmt2->rowCount();
... etc.

The MySQL Query:
SELECT
user,
COUNT(DISTINCT CASE WHEN date = CURDATE() THEN id END) as countToday,
COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 7 DAY THEN id END) as count7,
COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 14 DAY THEN id END) as count14,
COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 30 DAY THEN id END) as count30,
COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 365 DAY THEN id END) as count365,
COUNT(*) as countAll
FROM posts
GROUP BY posts.user
Access with PHP:
$res = $db->query($query); // set $query to my query
while($row = $res>fetch()){ // loop the result
// access your row here
echo $row["user"] // $row["countToday"] ...
}

Related

How to select users with their amount list and sum amount using SUM(CASE) with a date interval

I have a table which contains list of users and the amount they save per day. I want to select all the money they save per day and also list all their details(amount) they have saved.
Issue: I couldn't find the sum for that date interval
SELECT
cust_name,
ac_no,
amount,
SUM(CASE WHEN (trans_date > DATE_SUB(NOW(), INTERVAL 1 MONTH))
THEN amount ELSE 0 END) as todalTotal from contributions
where username = 'james12'
GROUP BY id
This is what I am trying to achieve
$que = mysqli_query($con,"SELECT cust_name,
ac_no,
amount FROM contributions
WHERE username='$username'
"
);
while($row = mysqli_fetch_array($que))
{
$sql =mysqli_query($con,"SELECT SUM(amount) as total FROM contributions WHERE trans_date > DATE_SUB(NOW(), INTERVAL 3 DAY) AND username='$username' ");
$rows = mysqli_fetch_array($sql);
echo $rows["total"] . "<br>";
echo $row["cust_name"] . "<br>";
}
$rows["total"] will appear the number of times
$row["cust_name"] appears which I don't want. I want
$rows["total"] to appear just once.
You have to select the coloumn and then tell where this is located. Then just use use SUM.
SELECT SUM(amount) AS AmountSaved
FROM yourtable
SQLdatabase
select user_name,sum(amount) as total_amount,date_format(trans_date,'%Y-%d-%m') as transDate
from table_name
group by user_name,date_format(trans_date,'%Y-%d-%m')

PHP SELECT to query date field plus 6 hours

I would like to query a date field to select all entries that are equal to or greater than current time + 6 hours. The commented first entry works, but it is the second entry that I am battling with. I know this syntax is nowhere near correct.
//$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND date_added >= CURRENT_DATE ORDER BY order_id DESC";
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND CURRENT_TIME >= date_added +6 hours";
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND NOW()>= DATE_ADD(date_added,INTERVAL 6 HOUR)";
This query will get your date_added value and add 6 hours to it and after will compare it with the CURRENT_TIME. I would suggest to use NOW() instead of CURRENT_TIME in mysql.
You're probably looking for the DATE_ADD (documentation) function. In your case:
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND your_date_field >= DATE_ADD(CURRENT_TIME, INTERVAL 6 HOURS)";
would likely do what you need it to.
try this query
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND CURRENT_TIME >= DATE_ADD(date_added, INTERVAL 6 HOUR)";

Select from database where date is less than a supplied date

I'm trying to pull rows from a database where the date is within two weeks of the current date, I'm using CodeIgniter and this is my model:
function GetToDoItems($userID)
{
$range = date('Y-m-d', strtotime("+2 weeks"));
$query = $this->db->query("SELECT * FROM FYP_Milestones
INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
WHERE FYP_Milestones.MilestoneDue < $range
ORDER BY FYP_Milestones.MilestoneDue ASC
");
return $query->result();
}
It runs this query:
SELECT * FROM FYP_Milestones INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID WHERE FYP_Milestones.MilestoneDue < 2016-04-14 ORDER BY FYP_Milestones.MilestoneDue ASC
I have a row in the database like so:
Considering 2016-04-07 is less than 2016-04-14 by 7 days I'm expecting that row alone to be pulled, but SQL is returning an empty result , why is this the case?
You actually don't need PHP for the range, use SQL:
WHERE FYP_Milestones.MilestoneDue < (CURDATE() + INTERVAL 2 WEEK)
Add single quotes to the date value like:
$query = $this->db->query("SELECT * FROM FYP_Milestones
INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
WHERE FYP_Milestones.MilestoneDue < '".$range."'
ORDER BY FYP_Milestones.MilestoneDue ASC
");

Select date for today

Table: id, confess, user_ip, time, url, loves, hate
Time is like 1413040760
$q = mysql_query("SELECT * FROM confessions where time >= unix_timestamp(curdate() + interval 1 day)") or die(mysql_error());
I need the best confess of day order by loves limit 1. This show my only blank, no results.
You're querying records that happened later than one day from now - i.e., in the future. Presumably, you don't have any records like that. You can change the + interval 1 day to - interval 1 day in order to get records that occurred up to 1 day ago.
$q = mysql_query("SELECT * FROM confessions where time >= unix_timestamp(curdate() - interval 1 day)") or die(mysql_error());
EDIT:
To answer the question in the comment, yes, it's possible to sort by loves - hates - just slap on an order by clause:
$q = mysql_query("SELECT * " .
"FROM confessions " .
"WHERE time >= unix_timestamp(curdate() - interval 1 day) " .
"ORDER BY (loves - hates) DESC" ) or die(mysql_error());

mysql , between and limit together

I want to get all the rows between a certain date interval , with the result set being at most 50 records. What can be the query ? I continuously getting errors on:
$sql = "SELECT DISTINCT userId FROM ".$TableName.
" where time BETWEEN (NOW() - INTERVAL "
.$USER_COUNT_DURATION.
" MINUTE AND NOW()) LIMIT 0, ".$limit." ;";
looks like paranthesis problem. "MINUTE AND NOW())" should be "MINUTE) AND NOW()"
$sql = "SELECT DISTINCT userId FROM ".$TableName." where time BETWEEN (NOW() - INTERVAL ".$USER_COUNT_DURATION." MINUTE) AND NOW() LIMIT 0, ".$limit." ;";

Categories