Inserting datetime into SQLSRV using PHP

0

I'm working with PHP and SQLSRV.

I need to insert a date into a field of type Datetime and I can not do it at all. At least not the ways I have found in Internet searches.

The last one I tried was this, because they said it worked:

if(isset($_POST['cadastrar'])){ 

    $dataInicio = $_POST['data'];

    $dataHoje = date("Y-m-d");

    $dataInicio['data'] = $_POST['data'];
    $data = DateTime::createFromFormat('l, j F, Y', $dataInicio['data']);
    $data = $data->format('Y-m-d H:i:s');

    $dataHoje['data'] = $_POST['data']; 
    $dataHj = DateTime::createFromFormat('l, j F, Y', $dataHoje['data']);
    $dataHj = $dataHj->format('Y-m-d H:i:s');

    $sql = "INSERT INTO [RDO].[dbo].[CAD_FUN] (DATA, DATAINI) VALUES (?,?)";

    $params = array($data, $data);

However, when you click on register, the following warning appears:

  

Fatal error: Call to a member function format () on a non-object

    
asked by anonymous 30.09.2014 / 14:39

1 answer

1

For your error message, you should be getting nothing or an invalid value for DateTime at line $dataInicio = $_POST['data']; . First of all you need to resolve this.

After successfully creating a DateTime , that is, after your $data = DateTime::createFromFormat('l, j F, Y', $dataInicio['data']); line works, simply delete the subsequent date formatting and pass the DateTime itself as a parameter to the query instead of passing a formatted string.

Note also that your code is overwriting the value of variables that you just left and you are setting variables that it will not use.

I basically removed from your code the extra lines that are disrupting or are useless:

if(isset($_POST['cadastrar'])){
        # $dataInicio  = $_POST['data'];
        # $dataHoje = date("Y-m-d");
        # Opção para criar DateTime a partir da data entrada no formulário:
        $data = new DateTime($_POST['data']);
        # $data = $data->format('Y-m-d H:i:s');
        # $dataHoje['data'] = $_POST['data'];
        # $dataHj = DateTime::createFromFormat('l, j F, Y', $dataHoje['data']);
        # $dataHj = $dataHj->format('Y-m-d H:i:s');
        $sql = "INSERT INTO [RDO].[dbo].[CAD_FUN] (DATA, DATAINI) VALUES (?,?)";
        $params = array($data, $data);
    
30.09.2014 / 19:18