How to save data in Mysql using prepared statments

3

I am changing the fields to save date in MySQL, from varchar to date , and I was in doubt about the correct way to include date fields in the database using prepared statments .

As I use DD / MM / YYYY during the script to do some comparisons etc, I wanted to make the change only in the time of including in the database, during insert .

I do not think you can use STR_TO_DATE( string, formato ) with prepared statments , as indicated in this answer , then , following this outra resposta I have adapted this:

if ($stmt = mysqli_prepare($mysqli, $sql)) {

mysqli_stmt_bind_param
(
    $stmt,
    's',
    date("Y-m-d", strtotime($dataDMY)),
...

And it worked, but debugging I get a notice undefined variable , which did not show up without putting date("Y-m-d", strtotime($dataDMY)) inside the bind::param execution. This way is correct? What is the ideal way?

    
asked by anonymous 28.09.2015 / 07:19

1 answer

3

The format coming from POST is string . You need to convert to a date instance.

$date = DateTime::createFromFormat('d/m/Y', $_POST['dataDMY'])->format('Y-m-d');

So the variable is ready to be inserted into the database in a field of type TIMESTAMP or DATETIME .

    
28.09.2015 / 15:54