bind_param() truncates input at first non-numeric character

Viewed 98

This snippet of my PHP code does not output the months, days, hours..etc. This is the code:

$dat = date('Y-m-d H:i:s');
$stmt = $LINK ->prepare("INSERT INTO NewUser VALUES (NULL, ?, ?, ?, ?)");
$stmt->bind_param('isss',$dat, $Phone, $User, $Pass);

/* execute prepared statement */
$stmt->execute();

And the output in my database is the year only. enter image description here

so, what am I missing after following everything written here?

1 Answers

You should always bind parameters as strings. The first argument in bind_param() is a list of types. They should all be s.

$stmt->bind_param('ssss',$dat, $Phone, $User, $Pass);

When you bind as an integer then PHP will cast the string to an integer. 2021-01-29 11:11:11 will be converted to 2021 because - is not a number. The rest of the string will be discarded.

The only time when you should cast something as an integer or as a string is when MySQL can't figure out the correct type. This is 0.001% of all cases.

If you are confused about mysqli API then please learn PDO instead. It is easier for beginners and offers more functionality.

Also, make sure that your column type in the database is DateTime not varchar or int! If you need the current date then use NOW() in SQL rather than PHP's date().

Related