I have a table with 12 timestamp columns and 3 other fields.
I can't change the field type on the timestamp columns.
I need to display all 15 fields to the user as m/d/y. Is there a way to format them all at the same time without having to apply DATE_FORMAT to each one?
I'd rather not have to do
SELECT DATE_FORMAT(field, '%c/%e/%y') AS field
for each one if possible.
I'm using mySQL & PHP and I don't care where the conversion happens.
You can write a simple date conversion routine in php such as this:
function mysql2table($date) {
$new = explode("-",$date);
$a=array ($new[2], $new[1], $new[0]);
return $n_date=implode("-", $a);
}
Which I stole from here: http://www.daniweb.com/code/snippet736.html#
Then simply loop through your SQL column results checking if the value is a date and converting it.
Have you considered using a database layer like MDB2 or PDO, which can convert the types for you? MDB2 has a date type, that displays YYYY-MM-DD format but could easily be turned into m/d/y with strftime and strtotime.
An example of using MDB2:
$dsn = "mysql://user#pass/db"; (not sure about DSN format, you might have to poke the MDB2 documentation)
$connection = MDB2::connect ($dsn);
$connection->loadModule ("Extended");
$rows = $connection->getAll ("your query", array ('date', ...), $parameters, array (paramater-types), MDB2_FETCHMODE_OBJECT);
if (MDB2_Driver_Common::isError ($rows)) throw new Exception ("Error!");
else { foreach ($rows as $row) { ...Do something... } }
You can find more documentation about using MDB in this way at MDB2 on InstallationWiki. Also there you'll find a list of MDB2 datatypes and what they are mapped to for display values. Also, Docs for MDB2_Extended will be a good source of info.
Edit: Obviously you'll have to use strftime and strtotime on each row separately. If you switch MDB2_FETCHMODE_OBJECT to MDB2_FETCHMODE_ORDERED or MDB2_FETCHMODE_ASSOC above, you can probably use a foreach loop to run strftime and strtotime on all of the rows that need to be reformatted.
I dont think it is possible, the query doesnt know what columns are until it returns the results, you have to tell it to change the formatting for each datetime.
Matt
Related
Trying to make a little Search feature for a user, so he can type in a date on a webpage made with HTML/PHP, and see which people in the db have registered as member on or after (a date). My user inputs the date in format 2015-10-01. This gets sent to a PHP page with a jqxGrid on it, populated with member details of members conforming to my query on the MySQL database (using PDO).
The query uses the operator >= on a string passed as (for example) "2015-10-01" in the WHERE clause, so I am using STR_TO_DATE to make the comparison work:
WHERE `lastUpdated` >= STR_TO_DATE( ? , '%Y-%m-%d');
With PDO, the ? later gets bound to the date (which was passed in as a string).
The db column for registration date is in DATETIME format, and in the db values look like: "2015-10-12 17:12:52".
My query returns an empty array every time, - and this after many hours of trying every conceivable permutation of date format, both in the MySQL statement and on the page that prepares the data for populating the grid.
Can someone show me what's wrong here?
Thanks!!
SP
Make it
WHERE `lastUpdated` > ?
and check your data and stuff.
Basically, you should never touch PDO until you get raw SQL to work.
okay, so here is the PDO version that works - passing in ? instead of the date:
function getJSONAllMembersByDate($PDOdbObject, $regDate)
{
try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>=?";//'$regDate'
$get=$PDOdbObject->prepare($membersByDateSQL);
$get->execute(array($regDate));
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
The fact that it works proves there were other errors in the file containing the jqxwidget (the version before I posted here). I certainly tried about a million different things to get this working.
I don't know if this counts as an answer, but at least it WORKS! There are so many variables in this problem - json, jqxgrid, pdo ... not forgetting that there are several ways to use PDO. I probably had several errors in different places.
(#apokryfos, the STR_TO_DATE was indeed unnecessary.)
In the end, this is what works:
In the PHP page containing the jqxGrid, the url sent to the server is:
url: 'my-json-responses.php?fct=getJSONAllMembersByDate®Date=<?php echo $fromDate ?>'
This $fromDate comes from the $_POST when the user typed in a date (in the format 2015-10-01) on the input page. When the PHP page containing the jqxGrid loads, it does
$fromDate = $_POST['regDate'];
The url "transits" through the file my-json-reponses.php, which contains many functions. It finds the right one:
if ($_GET['fct'] == 'getJSONAllMembersByDate')
{
$result = getJSONAllMembersByDate($connectionObject, $_GET['regDate']);
echo $result;
}
The $result is called on the file that contains all my PDO database requests, including:
function getJSONAllMembersByDate($PDOdbObject, $regDate) { try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>='$regDate'";
$get=$PDOdbObject->query($membersByDateSQL);
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
catch (PDOException $e)
{
echo "There was a problem getting all members with this search query.";
echo $e->getMessage();
}}
Note that I couldn't make the version using "?" in the query work at all, hence passing in the variable $regDate directly, with single quotes around the variable just to make life interesting.
This returns a nice list of all my users as of 2015-10-01 - but is presumably still open to MySQL injection attacks ...
But after this marathon of debugging I am happy enough for now. (All improvements welcomed, naturally!)
SP
How should I use MySQL's FROM UNIXTIME correctly in CDbMigration in Yii 1.x?
I have borrowed solution of converting current time given as timestamp, to MySQL's DateTime field from this answer and when just printing it:
echo 'FROM_UNIXTIME('.$base.')'."\n";
echo 'FROM_UNIXTIME('.$sixDaysLater.')'."\n";
everything seems fine:
FROM_UNIXTIME(1418223600)
FROM_UNIXTIME(1418742000)
But, when I'm trying to use the same technique as a part of my migration:
$this->insert('contents', array
(
'author_id'=>1,
'type'=>5,
'status'=>1,
'category'=>1,
'title'=>'title',
'body'=>'body',
'creation_date'=>'FROM_UNIXTIME('.$base.')',
'modification_date'=>'FROM_UNIXTIME('.$base.')',
'availability_date'=>'FROM_UNIXTIME('.$sixDaysLater.')',
'short'=>'short'
));
This fails -- that is, migration goes fine, but I can see in phpMyAdmin, that related fields for this record has been populated with zeros (0000-00-00 00:00:00), not with the expected value.
What am I missing? Is it, because values in insert are being encoded / escaped?
You can use CDBExpression instead:
new CDbExpression("NOW()");
I mean:
'creation_date'=>new CDbExpression("NOW()")
Or if you want to use FROM UNIXTIME you can do the same.
CDbExpression represents a DB expression that does not need escaping.
This question may be in part a duplicate of How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?, but I could not get any of the answers there working in my code. We're using MySQL 5.0.95, I don't know if that makes a difference, but I couldn't find a definitive answer that solved my problem.
Here's my code:
public function getZipCodes() {
// get records
$select = new Zend_Db_Select($this->db);
$select->from('postal_codes AS p', array(
'p.postal_code',
'p.city',
'p.county',
'p.area_codes',
's.rate',
// convert from datetime to mm/dd/yyyy format <== problem here
'CONVERT(varchar(11), s.date, 101)'))
->joinInner('sales_surtax_rates AS s', 'p.county = s.county', array())
->where('p.state = "FL"')
->order('p.postal_code');
$zip_codes = $this->db->fetchAll($select);
Zend_Debug::dump($zip_codes);
die();
}
I get a syntax error when trying to convert the datetime to a formatted string. I'm just not seeing what I'm missing, and other methods like FORMAT and cast didn't work for me either.
I'm well aware I can just loop through and reformat the datetime via PHP for each array item after pulling the records from the database, but I'm just trying to avoid the extra step(s) if I can and learn something new in the process.
You're using MSSQL syntax, it would appear, NOT MySQL's.
Try
DATE_FORMAT(s.date, '%m/%d/%Y')
instead.
Relevant docs: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
When I query a dateTime(6) PHP is truncating my 6 fractional seconds.
Here is an example of my php code:
$sql = 'SELECT date FROM tbl';
$statement = $connection->prepare($sql);
$statement->execute();
$statement->store_result();
$statement->bind_result($date);
while ($statement->fetch())
{
echo $date."\n";
}
This returns 2014-01-08 21:31:15 instead of 2014-01-08 21:31:15.995000 which is what is stored in the table. How can I get what is actually stored in the table?
The problem is with the PHP Adapter you are using to communicate with Mysql. As far as I can see you are using PDO adapter to fetch the query result. However, this adapter does not support fractional seconds (YYYY-MM-DD HH:MM:SS.F).
The PDO adapter supports YYYY-MM-DD HH:MM:SS and automatically formats the value of datetime columns to this format.
This is a bug in PDO adapter itself. Please find the link below for reference:
http://grokbase.com/t/php/php-bugs/11524dvh68/php-bug-bug-54648-new-pdo-forces-format-of-datetime-fields
You can format it to include it. The %f includes the six-digit microseconds.
SELECT DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s.%f') FROM tbl
It's crazy this still isn't officially supported by mysqli in PHP 7.1, but anyway, here's a work around.
select concat(`DateTime6`)`DateTime6` from ...
Basically casting it as a string worked for me, as ugly as that is.
This bug was finally fixed in PHP v7.3.0.
For related bug details: https://bugs.php.net/bug.php?id=76386
DateTime does not support split seconds (microseconds or milliseconds etc.)
http://www.php.net/manual/en/class.datetime.php
https://bugs.php.net/bug.php?id=51950
in your case you might save the value in MySQL as VARCHAR and case / convert it to datetime when reading it.
I had the same problem and nothing helped me except converting
i have a csv file that i'm interest and the date format is 20-Nov-2010 how do I format it for insertion into mysql accepted format for a field with Date as its type?
date("Y-m-d", strtotime("20-Nov-2010"));
Andreas' answer is a bit terse - in PHP this will return a string which you can splice
into your query:
$d=date("Y-m-d", strtotime("20-Nov-2010"));
$qry="INSERT INTO sometable (adate) VALUES('$d')";
But if you omit the punctuation, you can ad it without the quotes:
$d=date("Ymd", strtotime("20-Nov-2010"));
$qry="INSERT INTO sometable (adate) VALUES($d)";
A drawback of this approach is that strtotime() tends to always return some sort of date value - and sometimes not what you expect.
However you could do the parsing in MySQL, which is a lot more strict:
$d='20-Nov-2010';
$qry="INSERT INTO sometable (adate) VALUES(STR_TO_DATE($d, '%d-%b-%Y'))";
But remember to check for errors when mysql tries to parse the date.