How to get a mysql datetime field as a datetime in php? - php

I am new to PHP and MYSQL so this should be a pretty basic question.
I am querying a mysql database and getting three fields into an array. One of the fields type is datetime, but with my current query, it is being captured as a string.
This is my code:
$myquery = mysql_query ("SELECT id,text,when FROM messages ORDER BY cuando DESC");
$nrows = mysql_num_rows ($myquery);
for ($i = 0; $i < $nrows; $i++) {
$row = mysql_fetch_assoc ($myquery);
$when = $row["when"];
I've been googling and I think i have to use the AS operator in my query, but I dont' know how. How can I do this? If possible, just by changing the query...
Thanks!

in PHP: $when = strtotime($row["when"]);
in mySQL: SELECT id, text, UNIX_TIMESTAMP( when ) AS when FROM...

If you want a unix timestamp, you can either do it in your query or in php.
In your query:
$myquery = mysql_query ("SELECT id,text,UNIX_TIMESTAMP(when) FROM messages ORDER BY when DESC");
in PHP:
$when = strtotime($row['when']);
Edit: WHEN being a reserved MySQL keyword, this query will give an error. Use something else for your date field.

Related

Pulling records between two dates from a VIEW

I have a mysql datetime field that stores dates in the form '2013-12-25 00:00:00'
I need to select all records for any month in the table with a query like:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN '2003-11-01 00:00:00' AND '2003-12-03 00:00:00')
ORDER BY photodate DESC
LIMIT 30";
The above select query does the job fine.
In order to change the dates, I need to replace the '2003-11-01 00:00:00'AND'2003-12-03 00:00:00' with variables, so I set a variable with input data from two drop down lists for $startyear and $startmonth and convert it to what I think is the correct form using:
$startdate = $startyear."-".$startmonth."-01 00:00:00";
I do the same to the $enddate by adding 1 to the $startmonth.
My code then becomes:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN $startdate AND $enddate)
ORDER BY photodate DESC
LIMIT 30";
This does not work at all and gives a MySQL error. Having struggled with it for a month and finding nothing on any forum that uses variables instead of text, I am totally at a loss as to how it could be done. All help appreciated.
You are vulnerable to SQL injection attacks, which is why it's not working. You're producing the literal query
... WHERE (photodate BETWEEN 2003-11-01 00:00:00 AND 2013-12-03 00:00:00)
The 2003-11-01 and 2013-12-03 will be interpreted as a series of mathematical subtractions, and the 00:00:00 will be a simple flat-out syntax error. You need to, at bare minimum, quote those values:
... WHERE (photodate BETWEEN '$startdate' AND '$enddate')
^----------^-----^--------^--- note the quotes
so that mysql can see the WHOLE date as a date value, and not some arbitrary broken strings.
I guess you're missing some apostrophes... try this:
$sql = "SELECT * FROM images WHERE (photodate BETWEEN '$startdate' AND '$enddate') ORDER BY photodate DESC LIMIT 30";
You could have problems with the logic. In $enddate doesn't adding 1 to the start month give you 13?
Try printing out the contents $sql when the variables are in and see how it compares to the working $sql.
Please add apostrophes your query (and sanitize your variables using mysql_real_escape_string, PDO bind values, mysqli_real_escape_string) :
$sql = 'SELECT * FROM 'images' WHERE (photodate BETWEEN '.$startdate.' AND '.$enddate.') ORDER BY photodate DESC LIMIT 30';
A little reminder, you shall NOT use MySQL (deprecated, old.. and not that fast), if you're using MySQLi or going to use it, please sanitize your variables like this, as Marc B said it could break your script and your app security :
<?php
// Starting MySQLi Connection
$db = mysqli_connect("host", "user", "password", "dbname");
// Sanitizing your variables
$startdate = mysqli_real_escape_string($db, $startdate);
$enddate = mysqli_real_escape_string($db, $enddate);
// Query
$sql = "SELECT * FROM 'images' WHERE (photodate BETWEEN ".$startdate." AND ".$enddate.") ORDER BY photodate DESC LIMIT 30";
// Doing the query and print the result array
$var = mysqli_query($db, $sql);
print_r($var);
// Closing connection
mysqli_close($db);
?>
Please refer to to this for PDO way or to this for MySQLi way, you can also check the MySQL_real_escape_string into PHP doc but MySQL functions are deprecated since PHP 5.5

PDO MySQL get records with previous date

I've got a table with some columns. I want to filter some records using two of them, the one with INT type and second with DATETIME type. I'm using PHP PDO extension to connect with database and make some queries.
I'm trying to get the records from my table where datetime field is lower then given date, f.e.
<?php
$date = date("Y-m-d");
$this->db->query("SELECT * FROM `" . DB_PREFIX . "fanpage` WHERE `flag_warning` = ? AND DATE(`update_date`) < ?", array(1, $date));
?>
This returns NULL, but when I paste the same query into the phpMyAdmin window it shows me proper records. What is the problem?
Edit:
Fragment from query function:
public function query($sql, $params = array())
{
$result = array();
$result['query'] = $this->pdo->prepare($sql);
$result['query']->execute($params);
$this->lastResult = $result['query'];
unset($result['query']);
}
No need for the prepared statements at all
WHERE flag_warning = 1 AND update_date < CURDATE()
Use
$sqlStatement = $this->db->prepare("SELECT * FROM `" . DB_PREFIX . "fanpage` WHERE `flag_warning` = ? AND `update_date` < CURDATE()");
$this->db->execute(array(1));
$result = $sqlStatement->fetchAll(PDO::FETCH_ASSOC);
Now $result has what you need.
I've changed the column name to date_time_upd and it works right now, I think it's bug or something, maybe someone can explain that?
Edit:
Okay, I've figured it out. There was a fragment of code that checked for occurrence of the "UPDATE, DELETE OR INSERT" word in the query, and if there was a word like that the query result was not fetched. I've changed that to search for SELECT word, now everything is okay.

Python variables in other variables

I'm kind of new in python and want to make a MySQL select.
I want to select from the MySQL and add a variable to the query like this:
date = now.strftime("%Y-%m-%d)
sql = "SELECT * FROM table WHERE date='%s'" % date
(This offcourse, doesn't work)
I'm used to Php so this is kind of new to me as you can see :)
THANKS!
Maybe this does what you want...
date = now.strftime("%Y-%m-%d)
sql = "SELECT * FROM table WHERE date= '%s' "
sql = sql % (date)
cursor.execute(sql)
results = cursor.fetchall()
import time
now = time.localtime()
date = time.strftime("%Y-%m-%d")
sql = "SELECT * FROM table WHERE date='%s'" % date
I think this fragment does what you want?
Hope this helps

Looping out mysql data

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.
Edit: i used NOW() to store the date. Using the loop by longneck, how can ignore the time when checking if date is sameas previous? Should I explode? What's the best way?
you should use one query, sort it by date, and detect the change in the date as a signal to display the next 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>";
}
?>
I'm assuming that you want a list of the dates so that you can then do separate queries for each date's entries. Usually you would use a query like:
SELECT DISTINCT date_field FROM table_name ORDER BY date_field DESC
(this will do it newest-first, remove DESC to make it oldest-first)
Now, you probably don't want to do it this way, because it will require a lot of queries (one for each day's entries). It is more efficient to just order the entries by the date, and then use logic in your php to print out the headers. So you would use code like:
$result = $db->query("SELECT * FROM table_name ORDER BY date_field DESC");
$current_date = "";
while ($row = $result->fetch_array()) {
if ($current_date != $row["date_field"]) {
echo "<h3>{$row['date_field']}</h3>";
$current_date = $row["date_field"];
}
// Print your entry from $row here.
}
you would probably want to get that in your SQL statement: (assuming it is datetime type)
SELECT * FROM table
WHERE date BETWEEN '2009-9-8 00:00:00' AND '2008-9-8
23:59:59'
Then just do your normal loop through your results
Also have a look at the GROUP BY clause of the SELECT statement.

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