-5

Code below adds date in correct format but hours/minutes/seconds are inserted as 00:00:00.

$timestamp[] = 'date("2017-12-31 21:01:50")';

$i because I have this inside a a loop.

$sql = "INSERT INTO posts (post_id, username, content, timestamp, likes) 
VALUES ('$post_id[$i]', '$username[$i]', '$content[$i]', $timestamp[$i], 
'$likes[$i]')";

Result: Result

Spoody
  • 2,852
  • 1
  • 26
  • 36
PiotrZadka
  • 23
  • 3
  • 2
    `'date("2017-12-31 21:01:50")'` why the single quotes? those shouldn't be there. – Funk Forty Niner Jan 15 '18 at 21:30
  • The argument to `date()` is supposed to be a format string. – Barmar Jan 15 '18 at 21:31
  • You date function should be like this `date('Y-m-d H:i:s')`, and as @FunkFortyNiner why are you wrapping it with single quotes? it's treated as a string – Spoody Jan 15 '18 at 21:34
  • 3
    Presumably the idea is to run the mysql `date()` function, not the PHP one. The problem with that is that the whole point of that function is to only return the **date**, not a **datetime**, which is why the time portion is being lost. – iainn Jan 15 '18 at 21:40
  • @iainn Right. I'd say that is not far from an answer. – Funk Forty Niner Jan 15 '18 at 21:41
  • this questioin's unclear and where the OP is in all this, is unknown. – Funk Forty Niner Jan 15 '18 at 21:43
  • Hi, I removed single quotations as you guys advised but now i'm getting Error inserting row: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '21:01:50, '3')' at line 1 **The table type is timestamp** – PiotrZadka Jan 15 '18 at 21:49
  • if you want the current time of the insert, just use `NOW()` –  Jan 15 '18 at 22:01
  • I understand where the issue was. I passed into database as a simple string instead of date(). I'm using date later with posting post with current timestamp and works fine. Cheers for help! – PiotrZadka Jan 15 '18 at 22:07

1 Answers1

0

MySQL's date function returns a date without a time portion, which is why it's getting truncated to midnight.

You should be able to ignore the call to date entirely, and just pass the raw string - it's already in a format that MySQL will understand:

$timestamp[] = '2017-12-31 21:01:50';

$sql = "INSERT INTO posts (post_id, username, content, timestamp, likes) 
VALUES ('$post_id[$i]', '$username[$i]', '$content[$i]', '$timestamp[$i]', '$likes[$i]')";

(Note the added quotes around the $timestamp variable)

You should also look into using prepared statements, rather than building up your SQL string manually. It'd be both a security and readability benefit.

iainn
  • 16,826
  • 9
  • 33
  • 40
  • 1
    Yeah, figured out before you posted this. I just ignored it and added as you shown as simple string. I'm not doing anything later with this because my posts are generating timestamp anyway and adding that to database. Many thanks! – PiotrZadka Jan 15 '18 at 22:12