tags:

views:

40

answers:

1

For the past couple of hours I've been trying to format a MySQL timestamp using DATE_FORMAT and it doesn't do anything!

Perl Code:

use CGI;
use DBI;

my $q = new CGI;

# Database connection goes here

my $sth_select = $dbh->prepare(
    "SELECT DATE_FORMAT(timestamp, '%m/%d/%y') FROM foo"
);

$sth_select->execute() || die "Unable to execute query: $dbh->errstr";

if (my $ref = $sth_select->fetchrow_hashref()) {
    print $q->header;
    print " TIME: $ref->{timestamp}";
    exit;
}

Results

TIME: 

It doesn't print the formatted time at all, it is blank!

When I attempt to print the timestamp it doesn't print anything, but if I were to remove DATA_FORMAT and just simply do a SELECT timestamp FROM foo, then it prints the timestamp just fine, albeit not formatted though. Can somebody provide their insight on this matter, please?

+6  A: 

The hash returned has as keys column headers as provided by the database. When using a function like that, the column header is actually "DATE_FORMAT(timestamp, '%m/%d/%y')". Try modifying your SQL to be:

my $sth_select = $dbh->prepare("SELECT DATE_FORMAT(timestamp, '%m/%d/%y') AS timestamp FROM foo");
ysth
Or you could use `fetchrow_array` or `fetchrow_arrayref`, which don't care about column names.
cjm
Or: `foreach my $key (keys %$ref) { print "$key = $ref->{$key}\n"; }`
Jonathan Leffler
You sir just solved my problem! I was trying the 'AS' argument but instead of using 'AS timestamp' I was using 'AS formatted_timestamp'. Nevertheless I tried your suggestion and worked like a charm! If ever I meet you one day the beer is on me! Thanks one hell of bunch!
JCB
Comment directed @ysth but thanks for the insight too Jonathan!
JCB
@cjm Good looking out
JCB
@JCB, you should accept the answer by clicking on the checkmark near the score.
cjm
@cjm thanks! My first time posting a question here!
JCB