Multiple where queries on same column - php

I have a database of customers and would like to run a query to display how many customers have an active account on a month by month basis.
I already have the following to count how many customers have an expiry date for each month, but can anybody suggest a way to then count those with an expirydate >= now for each month?
<?php
$query = "select count(cid) as num_rows from customers WHERE expirydate LIKE '%-12-%'";
$result = mysql_query($query);
$row = mysql_fetch_object( $result );
$total = $row->num_rows;
echo "December: " .$total;
?>

Simple
mysql_query( "select count(cid) as num_rows from customers WHERE expirydate >= curdate()" );
Try to avoid mysql_* functions due to they are depricated.Instead use mysqli_* functions or PDO statements

The following will tell you have many customers have an expirydate per month for records on or after today.
SELECT
MONTH(expirydate) month, COUNT(cid) as count
FROM
customers
WHERE
DATE(expirydate) >= CURDATE()
GROUP BY MONTH(expirydate)
Do note though that as this groups only by month, records spanning multiple years may be misleading (3 July 2013 and 7 Jul 2014 would both count as July, for example).
You should look into the date and time functions and group by/aggregate functions for more information.

This query show you how much customers has expirydate after now. Correct your date format in STR_TO_DATE function for your case. MySQL STR_TO_DATE
SELECT COUNT(*) as `num_rows`, MONTH(STR_TO_DATE(`expirydate`,'%Y-%m-%d')) as `month`
FROM `customers`
WHERE STR_TO_DATE(`expirydate`,'%Y-%m-%d') > NOW()
GROUP BY `month`
Also try to use timestamp field type in your tables instead of varchar or etc.

Related

Display records in current month, using php and a mysql db

Im trying to display records in the current month from a column thats a timestamp.
This is my code
$query = "SELECT
donationid
FROM
donation
ORDER BY
donationid
WHERE
MONTH(donatedon) = MONTH(CURRENT_DATE())";
$query_run = mysqli_query($conn, $query);
$row = mysqli_num_rows($query_run);
echo '<h1>'.$row.'</h1>';
You're not checking the year, so you'll return records in the current month in any year, not just the current month.
Testing a function of a column prevents an index from being used to optimize the query. It's better to use a relational comparison if possible. You can simply create a formatted date for the beginning of the current month.
You also have ORDER BY in the wrong place, it has to be after the WHERE clause.
SELECT donationid
FROM donation
WHERE donatedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
ORDER BY donationid

MySql Query for Current Date

I have s MySQL Query where I want to pull data from my database but base it on the current month information
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND DATE (lbs_date) = CURDATE()) ORDER BY lbs_date DESC LIMIT 0,50");
This string pulls out the information for the current day.
I have also tried the below string but get no results from it:
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND MONTH(lbs_date) = (MONTH(NOW()) AND YEAR(lbs_date) = YEAR(NOW())
My table date format is as follow 2016-08-02
Or using PHP variables as so:
<?php
$start = date('Y-m-01'); // FIRST DAY OF CURRENT MONTH
$end = date("Y-m-t", strtotime(date("Y-m-d"))); // LAST DAY OF CURRENT MONTH
$sql = "SELECT * FROM lbs_trace_etrack WHERE lbs_agent = '".$slfirstname."' AND (lbs_date BETWEEN '".$start."' AND '".$end."')";
?>
I have done the following and it works
FROM lbs_trace_etrack WHERE lbs_agent = '$slfirstname' AND MONTH(lbs_date) = MONTH(CURDATE()) AND YEAR(lbs_date) = YEAR(CURDATE()) ORDER BY lbs_date ASC, lbs_time ASC
Thanks to all and Tijo for guidance
Assuming lbs_agent is a DATE field type as mentioned in comments, you could do this (note I am just showing the pertinent date part of your WHERE clause):
WHERE lbs_agent >= DATE_FORMAT(NOW() ,'%Y-%m-01')
It is important that you do not use a function call on the left (field definition) side of the WHERE comparison, as you will then not be able to leverage any index on that field. Doing this would require a full table scan with MySQL performing the function on this field for every row in the table such that the comparison can be made.
Feel free to use MySQL functions for the comparison value, as those would be calculated just once when the query is being planned. You would then be able to use an index on the field for quickly filtering the rows in the table that meet the criteria. From a query execution standpoint, this is basically that same as if your query has this WHERE clause:
WHERE lbs_agent >= '2016-08-01'
This is as compared to the examples in your question which would be executed as:
WHERE DATE(lbs_date) = '2016-08-03'
and
WHERE MONTH(lbs_date) = 8 AND YEAR(lbs_date) = 2016
Both of these would require full table scan since the values derived from the field are not able to be determined until the row is scanned.
You could try to extract the month, such as EXTRACT(MONTH from NOW())
you can use following code if it timestamp
MONTH(CURDATE())

Comparing date() in sql query

I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';

SQL Items within the Last Day

In my code, I am trying to find items in an activities table that are within the last day. This query is not returning any results, are there any problems with it? Is there a better query?
$curday = time() - (24*3600);
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > '$curday'";
There are two choices here, you can get and format the date through PHP or use SQL language to do it. I prefer to do it within the SQL, it also allows me to use the same query in a MySQL client.
This question is essentially the same thing: MySQL SELECT last few days?
This would be the new query:
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > DATE_ADD(CURDATE(), INTERVAL -1 DAY)";
you can try with unix function 'mktime' to get value of yesterday ..
as
$curday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
for reference
if your database will mysql only then you can extract yesterday in sql itself..
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY)
one more thing if timestamp is your column name don't put this column inside single quote ..
What you can use is DATE_SUB. This can be used as follows
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > date_sub(current_date, interval 1 day)
This way you don't need to work with current date in PHP
in Informix it would be (TODAY - 1) if the column is type DATE

MySQL query to pick specific DATETIME values?

Right now I have a MySQL table with one column called "date_time" that simply lists different DATETIME values (e.g. "2010-11-30 12:55:00"). Is it possible for me to construct a query that directly:
Selects DATETIME values where the month is the current month?
Selects DATETIME values where the days aren't passed days (e.g. tomorrow and until the end of the month?
An abstract query in my mind would look like:
$query = "SELECT * FROM meetings WHERE uid = " . $_SESSION['uid'] . "AND the DATETIME month is active month AND the DATETIME day is bigger than the active day"
Is this functionality possible in MySQL (did some searching but didn't find anything helpful), or will I have to use PHP functions later to filter this stuff out? Many thanks in advance.
MySQL has a ton of date formatting functions that would solve this for you:
Select by specific month...
SELECT ... WHERE MONTH(date_time) = MONTH(now());
Select by non-passed days:
SELECT ... WHERE DAY(date_time) > DAY(now());
Of course, these sorts of queries will pick out the same month/days in ANY records from ANY years. If you want to restrict to particular chunks of time, then you'll have to add more clauses.
Something like:
$query = "SELECT * FROM meetings WHERE uid = " . $_SESSION['uid'] . "WHERE EXTRACT(month from now()) = extract(month from date_time) AND EXTRACT(day from now()) < extract(day from date_time)

Categories