0

When I MySqlI Query to add a session info, I add the date as a string but when I look in phpMyAdmin the date is -2008. I echo out the date string and it is the correct date. Connection to the database is fine

PHP:

$endDate = date('d-m-Y',strtotime("+30 days"));
$sresult = mysqli_query($con, "INSERT INTO `sessions`(`session_id`, `session_token`, `session_serial`, `session_date`) VALUES (".rand(120, 1200).",3564578,1234586723, ".$endDate.")") or die("Failed to query database ".mysqli_error($con));
echo "Login success!!! Welcome ".$row['uid']."".$endDate; #Correct Date

phpMyAdmin:

session_id, session_token, session_serial, session_date,

161, 3564578, 1234586723, -2008,

Should Be:

session_id, session_token, session_serial, session_date,

161, 3564578, 1234586723, 19-09-2018

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
  • 1
    Show the output of `DESCRIBE sessions` in your question. Also, what does `var_dump($endDate);` output? – John Conde Aug 20 '18 at 19:53
  • Why don't you store the date in the db as an actual `DATE` type and then handle any formatting in your display code? This will make it easy to do date manipulations and comparisons in queries. – Patrick Q Aug 20 '18 at 19:59
  • @PatrickQ I'm trying to use the easiest way to get it all set up – The Gamerzs Aug 20 '18 at 20:20
  • 1
    Using the most appropriate datatype _is_ the easiest way to get set up. – Patrick Q Aug 20 '18 at 20:29

1 Answers1

1

You're not escaping the date value, and it seems like the field type for session_date in the database is an integer.

Since you're not escaping the value when generating the SQL, it's parsed as 19 - 09 - 2018, which depending on which month and day you run this, ends up being -2008 (nineteen minus nine minus two thousand and eighteen).

The first fix is to properly enclose the value (you should be using prepared statements for this as that would handle it automatically for you, but since you can trust the data):

... 1234586723, '" . $endDate . "')

Be aware that MySQL probably expects the date in the YYYY-mm-dd ISO format for date fields, so you probably want to change your generated date string to that as well.

Wolverine
  • 1,712
  • 1
  • 15
  • 18
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • `date('Y-m-d', strtotime("+30 days"));` will give you the date in 30 days in the format `YYYY-mm-dd`. – MatsLindh Aug 20 '18 at 20:13
  • Thxs for letting me know that it is using the $endDate format as an operation, I figured out to change the format to this "d m Y" is there a simple and easier way to do this? – The Gamerzs Aug 20 '18 at 20:16
  • 2
    Use a proper date field in mysql and use the format `Y-m-d` when inserting, and enclose it properly in quotes as shown above (or use prepared statements). – MatsLindh Aug 20 '18 at 20:20