Elena Politi
Elena Politi

Reputation: 181

Retrieving a date from MYSQL in a html form

Hi I have a form to add members with their birth date. The input field for birth date is:

<div class="form-group">
   <label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
       <div class="col-sm-9">
        <input name="data_nascita" type="date" class="form-control" id="data_nascita" placeholder="gg/mm/aaaa"  />
       </div>
</div>

Data are correctly uploaded to MYSQL and date format is

$data_nascita = ($_POST['data_nascita']);
var_dump($data_nascita); => string(10) "2003-04-15"

In the database is stored correctly, and it appears as

2018-12-14 18:50:48

I want to have the possibility to edit the information about the person (i.e. changing the birth date), and I created an edit file where all the database information is retrieved and appears in form fields that can be edited and updated in MYSQL.

Everything works fine except for dates, which appears as gg/mm/aaaa

The code I used for retrieving data is as usual:

<?php
    $query = "SELECT data_nascita FROM volontari WHERE id_volontari = '$id'";
       $res = $mysqli ->query($query);
       $row = $res->fetch_array (MYSQLI_ASSOC);
       $data_nascita = gira_data_db($row['data_nascita']);

    function gira_data_db($data)
    {
        $array = explode( "-" , $data);
        $array2 = array($array[2], $array[1], $array[0]);
        $testo = implode( "/" , $array2);
        return $testo;
    }
?>
<div class="form-group">
 <label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
    <div class="col-sm-9">
      <input name="data_nascita" type="date" class="form-control" id="data_nascita" value="<?php echo $data_nascita ?>" />
    </div>
</div>

The date retrieved is

var_dump(gira_data_db($row['data_nascita']);) => string(10) "15/04/2003" 

However in my form field the data appears as 00/00/0000. If I echo the date in an input field type=text, it appears correct.

Am I doing something wrong?

Upvotes: 0

Views: 1163

Answers (1)

Mahsa
Mahsa

Reputation: 383

The problem is when you explode by '-' array[2] is '14 18:50:48' and it's not valid value for input with date type.

simply change gira_data_db function as follows:

function gira_data_db($data)
{
    return date("YYYY-MM-DD", strtotime($data));
}

I hope it would help you

Upvotes: 1

Related Questions