Timestamp returned as weird string - php

When I select a timestamp from the cassandra database via PDO (YACassandraPDO is also installed), I get the following output;
Bý£1€
Identified as a string(8) in a var_dump
This value should be December 17th 2013 00:00:00
As a guess, I tried $arr = unpack("l", $raw['date']); which results in
Array([1] => 1107361792)
But converting from epoch, this equals: 2005-2-02
Can anyone tell me what I'm supposed to do?
UPDATE
By the way, the timestamps show up just fine in the CQL commandline and DevCenter.
UPDATE 2
Here's the method I use to select the rows;
function getAny($limit=100)
{
$stmt = $this->pdo->prepare("SELECT * FROM \"".$this->tableName."\" LIMIT $limit;");
if($stmt->execute() === false)
{
$this->logError($stmt, "getAny");
return false;
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Check that the timestamp is correct at the time of insertion into the database. The epoch time string you should have is 1387238400

Not really an answer, but it seems to be as good a solution as it's going to get; I simple changed the column types to bigint to store the epoch time & it's working fine now. If anyone ever finds out what was going on, I'd love to know!

Related

PHP/MySQL/PDO search on date from database

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&regDate=<?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

PHP How to return datetime(6) from Mysql?

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

SELECT DATE_FORMAT(NOW(),'%m-%d-%Y') in php is not working well

can anyone help me with this:
$querydate ="SELECT DATE_FORMAT(NOW(),'%m-%d-%Y') AS dat";
$query = mysql_query($querydate);
$row = mysql_fetch_assoc($query);
$fecha = $row['dat'];
-2013-31+07 it is returning -2037
And i want it to return today's date
31-07-2013
Try this
SELECT DATE_FORMAT(NOW(),'%d-%m-%Y') AS dat
Here you have more info for the format of date
Given your code example, a value of '07-31-2013' should be assigned to fecha;
If you want the day before the month, then change the format string to '%d-%m-%Y'.
Evaluated in a numeric context, the expression -2013-31+07 should return -2037. That is expected behavior.
But we don't see in your code where this evaluation is taking place.
There could be reasons for pulling the date that aren't apparent in your question, but if your MySQL implementation is on the same machine as your php code then you could get the results your looking for by running:
$fecha = date("d-m-Y");
And save yourself the database call.

PHP: why is strtotime() returning "NOW()"?

I'm calling strtotime() on a formatted datetime string and for some reason it always returns NOW()...
If my formatted datetime string (stored in the last_seen attribute) is: 2013-06-13 07:13:04
and I write the following code:
echo $user->last_seen;
echo date('F j, Y', strtotime($user->last_seen));
The output I get is:
NOW() January 1, 1970
What on earth is going wrong here??? This is definitely not the expected result. The string is stored in a MySQL database, if that makes any difference.
Edit: by request, the code used to create the attribute in the database is:
$user->last_seen = date('Y-m-d H:i:s');
$user->save;
Edit 2: by request, the code used to pull the users table, with the user we want, is:
$user = User::find($user_id);
(not very helpful, lol).
Edit 3: if I var_dump($user->last_seen) the result is:
object(Laravel\Database\Expression)#40 (1) { ["value":protected]=> string(5) "NOW()" }
Edit 4: If I echo var_dump(strtotime($user->last_seen)) the result is:
bool(false)
Edit 5: this problem was a result of me being an idiot, but some fine debugging was done by everyone who posted. Read the answers if you are interested.
First of all You check the return value of strtotime($user->last_seen)
If strtotime($user->last_seen) returns false then $user->last_seen may be empty or not a valid Date and Time Formats
var_dump(strtotime($user->last_seen))
Your problem is most likely not in the select clause, but lays there where you store your data.
When you are inserting the time in the database, you are probably doing
insert into myTable (fieldname) values ('now()');
instead of
insert into myTable (fieldname) values (now());
So you need to lose the quotes there...
You are NOT storing the time in the database, but the string now() ...
The best thing you could actually do is change the database column type from varchar to DateTime, so even the database knows it's a DateTime. Then you avoid having to cast it back to DateTime in PHP.
Oh dear god.... I'm going to kick myself for this one. I did a project wide Ctrl+F for last_seen and I discovered that in my routing scheme I had this:
Route::filter('before', function() {
if (Auth::check()) {
$user = Auth::user();
$user->last_seen = DB::raw('NOW()');
$user->save();
}
});
Walks away with tail between legs...

Formating multiple mySQL date fields at the same time

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

Categories