Use PHP date() as SQL date - php

I'm trying to create a SQL query that finds results from this day in history (ie today's date, not including the year)
I get the current date in PHP:
$today = date("Y-m-d", time());
I get no errors but also no results are returned when I use $today in this query:
SELECT name, date FROM births WHERE MONTH(date) = MONTH($today) AND DAY(date) = DAY($today)
There are two rows in the date column that contain today's date in Y-m-d format. I'm not sure what's going on here. Is it because of an incompatible use of the variable? This is what my table structure looks like:

dates in mysql should be surrounded in single quotes so this is what you are after
$today = date("Y-m-d", time());
$sql = "SELECT name, date FROM births WHERE MONTH(date) = MONTH(`{$today}`) AND DAY(date) = DAY('{$today}')";
$query = mysqli_query($con, $sql);

Related

How to query db and select from where PHP datetime is today

I have data inserted into table 'dnt' with colum date being php datetime.
$date = time();// this was inserted into the db as :1481811673
$today = time();
"SELECT * FROM `dnt` WHERE 'date' = '$today'";
You cannot compare a timestamp with date today as timestamp changes per second so to compare right, you need to convert the timestamp stored in db into a dateformat and then compare that date with today date. You can do it as follows:
$today = date('Y-m-d'); // date today in format - YYYY-mm-dd
//your query
"SELECT * FROM `dnt` WHERE DATE_FORMAT(FROM_UNIXTIME(dnt.date), '%Y-%m-%d') = '$today'";
I hope it helps
This appears to answer your question http://www.tomjepson.co.uk/mysql-select-from-table-where-date-today/
tldr;
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Short and simple:
$stmt = "SELECT * FROM `dnt` WHERE 'date' = '".date('Y-m-d')."'";
To work with a timestamp:
$now = new DateTime();
$stmt = "SELECT *
FROM table
WHERE date = '".$now->getTimestamp()."'";
Detail
What the above query does is to SELECT all (*) FROM table dnt WHERE date =
the date() function in PHP returns a certain date based on the parameters you put in. the Y is for the years, the m for the months and the d for the days. So it will become date('Y-m-d') which will return 2010-01-01 for example.
the '". and ."' are to escape the php function so that it will not give you any syntax errors.
Besides what Peter said - the query is incorrect. You are comparing the date string value (date between single quotes) to a timestamp.
$stmt = "SELECT * FROM `dnt` WHERE `date` = '".date('Y-m-d')."'";

convert Unix Time stamp and sort data in mysql query

I am trying to query a small database by date, my date table data is stored in time 2014-02-04 . how can I convert that and check it against todays date.
This is what I have but I am getting a few errors
$q = 'SELECT count(*) as count FROM SHOW WHERE date('Y-m-d', strtotime
('SHOW_DATE') ='.$db->qstr(date()).' AND CONTACT='.$db->qstr($name);
if(!$rs = $db->execute($q)){
force_page('core', 'error&error_msg=MySQL Error: '.$db->ErrorMsg().'&menu=1');
exit;
} else {
$today_count = $rs->fields['count'];
$smarty->assign('today_count',$today_count);
}
Thanks a lot.
You can convert show_date to a date format using FROM_UNIXTIME function. And then compare the date part of it with your input date value.
Example:
SELECT count(*) as count FROM `SHOW`
WHERE date( from_unixtime( `SHOW_DATE` ) ) = ? AND CONTACT=?
Use prepared statement to bind input values to the place holders.
To find a row containing a DATE matching the current date, use CURDATE():
SELECT column FROM table WHERE col_date = CURDATE()

Getting the data for each month

So what I want to do is basically this:
Month and Year:
-All the data sent on that month and year
For example:
February 2013:
-The posts on this date
March 2013:
-The posts on this date
and so on.
I have a date column on my table and it has the following format: day.month.year
I am using PHP and MySQL.
I have my own MVC framework that I'm using. I will simplify it to make it more understanble here. The function to fetch data:
function selectAll($sql){
$find = $this->prepare($sql);
$find->execute();
$fetchdata = $find->fetchAll(PDO::FETCH_ASSOC);
return $fetchdata;
}
And the code to get the dates :
$sql = "Select YEAR(Date) AS year, MONTH(Date) AS month, Headline from blog";
$data = $this->db->selectAll($sql);
foreach($data as $key => $value) {
$date[] = $value['month'].'.'.$value['year'];
}
$dateunique = array_unique($date);
This give me the results for the dates but I cannot figure out how to put the correct data under each date.
Convert the varchar date field into exact date using
str_to_date function
Using DATE_FORMAT you can select month wise record
Where $input is %Y-%m format // ex: 02-2013-> feb 2013
SELECT * FROM `table`
WHERE DATE_FORMAT(str_to_date(`date_column`, '%d/%m/%Y'), '%Y-%m')= '".$input."';
Use DATE_FORMAT mysql function.
Example
SELECT DATE_FORMAT(date_field,'%M') as Month,DATE_FORMAT(date_field,'%Y') as Year FROM table_name
and then debug result of query you will see two extra column for month and year then display it as your desire.
if date_field is varchar then use str_to_date mysql function.
SELECT STR_TO_DATE(date_field,'%M') as Month, STR_TO_DATE(date_field,'%Y') as Year FROM table_name;
OP question update
Try GROUP_CONCAT
SELECT
*,
GROUP_CONCAT(created) AS month
FROM
table_name
GROUP BY MONTH(created) DESC;

How to insert and read time/date in MySQL/PHP?

I want to read the single day, month and year, without adding 3 extra MySQL-rows, in this format (with PHP):
day: 01
month: Jan, Feb, Mar..(first three letters)
year: 2011
This is table and PHP script, which I use now:
I add the date with PHP:
mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".m.".".Y)."');");
I read it out with:
$query = "SELECT * FROM news";
$result = mysql_query ($query);
while ($row = mysql_fetch_assoc ($result)) {
echo $row['time'];
}
MySQL table:
news:
time(text):
"27.03.2011"
Query should be:
mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".M.".".Y)."');");
M instead of m gives you the 3 letter textual representation of the month.
Get it with:
while ($row = mysql_fetch_assoc ($result)) {
echo date( 'd', strtotime( str$row['time'] ) );
echo date( 'M', strtotime( str$row['time'] ) );
echo date( 'Y', strtotime( str$row['time'] ) );
}
Read more on:
http://php.net/manual/en/function.date.php
you can either do it in PHP, check the strftime function or use in SELECT something like
SELECT DAY(date) as day, MONTH(date) as month, YEAR(date) as year FROM table
and in php you would acccess it as $result['day']. $result['month'] etc. the "date" in SELECT query is of course the name of the column in which you store your date. I would recommend strftime
You can use MONTH(), DAY(), YEAR() Mysql functions., i.e,
SELECT MONTH(`time`) AS `month`, DAY(`time`) AS `day`, YEAR(`time`) AS `year` FROM `news` [...]
SELECT *, substring(1,2) as day, substring(4,2) as month, substring(7) as year FROM table
Also you can(and should) use date table format and use DAY(), MONTH(), YEAR() functions
You should be using a DATETIME column in your mysql table. MySQL is then responsible for storing the date in its own internal format, and you can retrieve it in any format you need.
To insert the current date, you can simply
INSERT INTO news (...,`time`) VALUES (...,NOW())
To retrieve it in the format you want, use
SELECT DATE_FORMAT(`time`, '%d.%b.%Y');
Documentation on MySQL DATE_FORMAT()

Getting any rows which were added before a certain date

Would this be possible? I've used this to insert the date into a field called "date":
$date=date("m/d/y");
$sql="INSERT INTO pool (date) VALUES('$date' )";
$result=mysql_query($sql);
I've used this statement to get the date a week ago:
$variable = date('d-m-y', strtotime('-1 week'));
So how would I SELECT any rows which were added last week?
Instead of storing your dates as m/d/y, you should store them as Y-m-d :
$date=date("Y-m-d");
$sql="INSERT INTO pool (date) VALUES('$date' )";
In the database, you dates will then look like 2011-04-09.
That format is much easier to work with : alphabetical comparisons will work.
Which means that searching for rows that are older than a certain date would become something like this :
$variable = date('Y-m-d', strtotime('-1 week'));
$query = "select * from pool where date < '$variable'";
Also note that instead of working with a date field which is a varchar (or an equivalent) in your database, you could use a DATE column -- which would allow to to work with date and time functions in MySQL.
If the date field is a proper date type you can do < or > in your sql query. For example -
SELECT * FROM table WHERE date > '$date'
If you want everything from 1 week ago to now you can do something like the above or
SELECT * FROM table WHERE date BETWEEN '$date' AND NOW()

Categories