0

I've got a database with multiple rows and columns, which are grabbed with PDO.

$sql     = "SELECT timestamp FROM table";
$stmt    = $dbh->prepare($sql);
$results = $stmt->execute;
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

One of the database columns is timestamp which is a 10 digit unix timestamp. I'd like to convert this server side to a readable format before sending it to the browser.

This is how I'd like it to be formatted, but I know it needs to be done on every row and this is where it trips me up. Possibly a foreach loop?

$results['timestamp'] = date('H:i\, l jS \of F Y', $results['timestamp']);
2
  • 2
    Sounds like a good possibility. Have you tried it? Commented Oct 10, 2014 at 13:59
  • @JayBlanchard Yes. It might work with if my query returned a single row, but as it's multiple rows I need to iterate through every one. Commented Oct 10, 2014 at 14:40

2 Answers 2

3

Much simpler to do that in the DB directly, since the DB will already be "looping" on the exact same data, saving you having to reloop in client-side code:

SELECT DATE_FORMAT(timestamp, '%H:%i, etc...') FROM table

The format codes are documented here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Sign up to request clarification or add additional context in comments.

4 Comments

do you need the backticks for timestamp? dev.mysql.com/doc/refman/5.5/en/datetime.html
Ok. I thought you needed to escape the reserved words.
You need, unless they are permitted: MySQL permits some keywords to be used as unquoted identifiers because many people previously used them. Examples are those in the following list: ACTION BIT DATE ENUM NO TEXT TIME TIMESTAMP
That is one suggestion, but I might need to modify other columns. This approach is neat but will only work with the keywords above, such as DATE_FORMAT. A foreach loop will let me modify this timestamp example, and any other variables that need things appended to them/modified before being submitted to the user.
0

Figured it out :)

array_walk($results, function(&$value) {
    $value['timestamp'] = date('H:i\, l jS \of F Y', $value['timestamp']);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.