Search code examples
phpdate-formatting

PHP: Inserting date as string turns to -2008


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


Solution

  • 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.