Check a certain data from a column - php

is possible to check a certain data from a column ?
for exemple, I have a column called 'added' and values is something like '2011-04-18 10:44:42'
and is possible to check from column only the date '2011-04-18'
$date = sqlesc(get_date_time());
$res = mysql_query("SELECT id, username FROM users WHERE added =
$date ORDER BY username") or print(mysql_error());

SELECT id, username
FROM users
WHERE added >= '2011-04-18'
AND added < '2011-04-18' + INTERVAL 1 DAY

if i understand your question correctly you need mysql DATE_FORMAT() It will allow formatting your database date value to format of YYYY-MM-DD
use something like :
$res = mysql_query("SELECT id, username FROM users WHERE DATE_FORMAT(added, '%Y-%c-%d') =
$date ORDER BY username") or print(mysql_error());
hope that helps

The simplest solution... works for DATETIME and all text type fields (such as VARCHAR, TEXT, etc).
$date = sqlesc(get_date_time());
$res = mysql_query("SELECT id, username FROM users WHERE added LIKE '$date %'
ORDER BY username") or print(mysql_error());

Related

SQL - Select unixtimestamp as date

I am trying to select an unixtimestamp column from my database, as readable date time:
SELECT count(*) FROM users WHERE user_by="Admin" AND expire(FROM_UNIXTIME(unixtime),'%Y-%m-%d')='2015-10-02'
Above gives me this error:
#1305 - FUNCTION database_maindb.expire does not exist
How can I select the unixtimestamp from column expire as datetime, in the format: year-month-date?
assuming your database field is called "expire":
SELECT count(*) FROM users WHERE user_by="Admin" AND FROM_UNIXTIME(expire,'%Y-%m-%d')='2015-10-02'
see http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime for details
You don't need to select is as the YMD date stamp, you could do something such as (using your tags)
$query = "SELECT * FROM `table`;";
$result = pdoObject->queryMethod($query);
$result= pdoObject->fetchAssocMethod($result);
$date = date("Y-m-d", $result['epochCol']);
I hope this helps.

MySQL, get data between two dates that are formatted as strings

Would be grateful for some help!
Database Tables are set up like this:
id(varchar),
temp(varchar),
humi(varchar),
time(varchar)
Then I thought the user to input the ID, start date and end date.
The problem is how the string in the Time column is formatted, example: 18/03/14: 21:52:36
The user should not have to enter the time, just the date.
I thought it would be possible to do in a similar way:
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND time BETWEEN '$start%' AND '$stop%'");
But it did not work.
Is it possible to do this with a sql query when the date is stored in such a way?
Regards
. Anders
Edit:
It did not work, probably because I'm doing wrong though = /
If I do this:
$start= "13/02/14 : 12:17:34";
$stop = "13/02/14 : 12:36:18";
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN '$start' AND '$stop'");
..the data will appear as expected
But when I try to to use str_to_date () ,it did not work as I thought, or it did not come out any data at all.
$start= "13/02/14";
$stop = "10/02/14";
$id = "3E000004C6DB8D28";
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN str_to_date('$start%', '%d/%m/%Y') AND str_to_date('$stop%', '%d/%m/%Y')");
edit2:
Do not really know what I was doing weird the first time, but now it works with this code:
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN '$start' AND '$stop'");
You need to use str_to_date():
WHERE id = '$id' AND
tid BETWEEN str_to_date('$start%', '%d/%m/%Y') AND str_to_date('$stop%', '%d/%m/%Y')
Obviously, you can also do this in the application before inserting the values into the query. If so, convert the values to 'YYYY-MM-DD' format.

PHP Matching the output of 2 codes

I need to match the result format of 2 code:
I need to get the output/format of this:
$event_day = $year.'-'.$month.'-'.$list_day; // $event_day
match this:
DATE_FORMAT(date,'%Y-%m-%d')
Full code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
My problem is that $event_day is only displaying events for: October, November and December.
I had a similar problem with this code below:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date LIKE '$year-$month%'
AND active = 1";
and it was fixed with this code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
Anyone know how I could sort this out?
If you are simply trying to match dates in a SQL query, which is what you look like you're after, you can just pass the date as a string with a # on each end. This will tell SQL to parse the string as a date and the format you give it in is not really important. The exception to this is it can get confused between US/EU date formats like dd/mm/yyyy vs mm/dd/yyyy.
$query = "SELECT title, DATE_FORMAT(myDate,'%Y-%m-%d') AS formattedDate
FROM table
WHERE user_id = '$session_user_id'
AND (myDate BETWEEN #$year-$month-1# AND #$year-$month-1#)
AND active = 1";
This format should work but your query is select records that fall between the same date so you'll only get records that are actually on that date. You might as well just use WHERE date = #$year-$month-1#
edit: this assumes your date field datatype is correctly set up in the database as a date/time.
edit2: "date" is often a reserved word in databases and shouldn't really be used for field names and variables. See edited code above.
In addition I would suggest using php to format the date using the date() function rather than format it in the query. This allows more flexibility to actually use the date in your script.

Getting records between 2 dates someone chooses php mysql

I'm trying to get records between 2 dates. The dates are entered in the form "yyyy-mm-dd" into a input type="text" (so for example I would type "2011-02-15" into a text input) and then posted to the next page which has the query:
$start = $_POST["start"];
$end = $_POST["end"];
$sql_query = "SELECT * FROM actionlist WHERE date>='{$start} 00:00:00' AND date<='{$end} 23:59:59' ORDER BY id";
$result = mysql_query($sql_query);
The records in the table "actionlist" have a field called "date" and this is entered automatically when creating the record by using "$date = date('Y-m-d H:i:s')".
Anyway, I can't seem to get any records to be selected. Do I need to process my $start and $end variables somehow? Thanks in advance.
You can use between to get the information you want
$sql_query = "SELECT * FROM actionlist WHERE date BETWEEN '$start' AND '$end' ORDER BY id";
But you need to make sure start and end are valid, and escaped,etc.. to prevent sql injection, and the like
$start = mysql_real_escape_string(trim($_POST["start"]));
$end = mysql_real_escape_string(trim($_POST["end"]));
$sql_query = "SELECT * FROM actionlist WHERE date BETWEEN '".$start." 00:00:00' AND '".$end." 23:59:59' ORDER BY id";
$result = mysql_query($sql_query) or die(mysql_error());
Edit: the trim() in case you have some unwanted space in your input forms; a bit of sanitation then, and use BETWEEN, as everyone has suggested right before me (damn I'm so slow at writing...)
Edit 2 based on comment below
Try that way
SELECT * FROM actionlist WHERE date BETWEEN 'start' AND 'end'

How can I ignore time for NOW()?

I have a mysql database of entries
with dates. So what I want is to show
all the dates in my database and then
under each date, I want to show all
the entries in the database entered on
the specefic date. I am thinking of
two loops but I don't know how to
write the condition to display all the
dates in my database before I loop out
the entries under that date.
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) { if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date']; }
echo "<p>{$row['name']}</p>"; }
?>
In a previous question (Looping out mysql data), I resulted in using this code. It pulls the date and time from MYSQL, and I used NOW() to store both date and time. How can I make it ignore the time so I can achieve what I want?
as David Andres mentions in the comment, DATE() extracts the date part of a date or datetime expression. so you can do the following:
<?php
$sql = 'SELECT DATE(start_date) AS start_date_date, name FROM events ORDER BY start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date_date'] != $prev_date) {
echo "<h1>$row[start_date_date]</h1>\n";
$prev_date = $row['start_date_date'];
}
echo "<p>$row[name]</p>";
}
Use CURDATE() instead of NOW().
Try it with a condition like this:
SELECT * FROM `events` WHERE DATE(`start_date`) = '2009-09-09';
This'll get you all events from the database for Sep 9th 2009. I think that's what you're asking for, is it?
Untested code that I will probably need someone to correct, but here goes:
SQL to retrieve all the dates that exist in the table:
$sql_get_dates = 'select start_date from events order by start_date distinct';
And, assuming start_date is a DATETIME type, the SQL to get all events on a given date:
$sql_get_events = 'select * from events where date(start_date) = "2009-08-09"';
Instead of just selecting the date, you could use some of the MySQL time functions to truncate the date.
$sql = "select date_format(start_date, '%Y-%m-%d') as fstart_date, name from events order by start_date";
Of course, you'll have to change start_date to fstart_date within the PHP code.
Check out the Mysql reference page for DATE_FORMAT().

Categories