Skip to content
Advertisement

php -> sql missing leading zero

I am passing ID´s, with a query to a SQL database. The ID is generated by new DateTime(), which I format afterwards. The whole workflow works, SQL database connection is established and the ID´s are added.

The problem is the leading zero´s, for example todays date 08.10.2021. Those is shown as 08102021.. in PHP but added as 8102021.. in sql.The leading zero is gone. I already played around with different column types in sql, like nchar, varchar, int etc. each time the same problem.

What do I miss?

    $date = new DateTime();
    $date = $date->format("dmYHisu");

    $addQuery = "INSERT INTO nodes (id) VALUES ($date)";
 
    if (sqlsrv_query($connection, $addQuery)) {
        echo "Node added.";
    } else {
        die (print_r(sqlsrv_errors(), true));
    }

I also hardcoded the passed value, each time the same problem.

Advertisement

Answer

leading zero mean it’s string so you have to put single quote to your $date variable like this

$addQuery = "INSERT INTO nodes (id) VALUES ('".$date."')";
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement