Insert a field of type DATE in MySQL from a query prepared in PHP

0

Good morning. I have a problem when inserting a date in a MySQL table from PHP with a prepared query. I have the following block of code:

$query = "INSERT INTO ARTICULOS (CODIGO, FECHA) VALUES (?, ?)";
$resultado = mysqli_prepare ($conexion, $query);
if ($resultado == false)
{
     echo "Error fatal";
     mysqli_close($conexion);
     exit();
}
$codigo = "5555";

// Cadena con la fecha
$cadena_fecha_mysql = "2015-08-24";
$objeto_DateTime = date_create_from_format('Y-m-d', $cadena_fecha_mysql);

$ok = mysqli_stmt_bind_param ($resultado, "ss", $codigo, 
                              $objeto_DateTime);
if ($ok == true)
{
    echo "Estoy en 1<br>";
    $ok = mysqli_stmt_execute($resultado);
    if ($ok == true)
    {
        echo "Estoy en 2<br>";
    }
    else 
    {
        $error = mysqli_errno($conexion);
        echo "Error $error en la instruccion $query<br>";
        echo "2 ha fallado<br>";
    }
}
else 
{
    echo "1 ha fallado<br>";
}

mysqli_stmt_close($resultado);
mysqli_close($conexion);   

It is printed: I'm in 1

And there is an exception in the mysqli_stmt_execute line:

  

Catchable fatal error: Object of class DateTime could not be converted   to string

I have already tried many things and nothing works for me. The table field ARTICULOS is type DATE (neither DATETIME or TIMESTAMP )

    
asked by Carmen Encinas 29.08.2017 в 22:13
source

2 answers

0

That I remember you could send the String directly to the query, but preferably it uses single quotes.

On the other hand, the MySQL format that accepts date is YYYY-mm-dd, therefore your function should be:

date('YYYY-mm-dd', $cadena_fecha_mysql);
    
answered by 29.08.2017 / 22:44
source
0

Try first converting the String to Timestamp :

$timestamp = strtotime($string);

And then in Date :

date("Y-m-d", $timestamp);

Another way would be using a DATE_FORMAT:

DATE_FORMAT('2009-10-04', '%W %M %Y')
    
answered by 29.08.2017 в 22:45