1

I have a MySQL table with a field that is date format and can be NULL.

I'm updating an old PHP update file to use mysqli prepared statements and having problems saving date field values to the DB resulting in

Fatal error: Uncaught mysqli_sql_exception: Incorrect date value:.....

Minimum reproducible code below:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); //force detailed report and die

require_once('../Connections/mysqli_connect.php');

//---------------------------on submit, do ------------------------------------

if ((isset($_POST["update"])) && ( $_POST["update"] == "editnoteform")) {
    
    //Prepare dates
    if(!isset($_POST['forecastdate'])){
        $forecastdate = NULL;
    } else {
        $forecastdate = $_POST['forecastdate'];
    }
    
    //---------------------------update record ------------------------------------
    
    $record_update = mysqli_prepare($conn, "UPDATE CONTNOTES SET FORECASTDATE=? WHERE NOTESID=?");
    mysqli_stmt_bind_param($record_update, "di", 
        $_POST['forecastdate'],
        $_POST['notesid']
    );// bind parameters
    mysqli_stmt_execute($record_update);// execute query

}

//---------------------------get existing data------------------------------------

$rs_notes = mysqli_prepare($conn, "SELECT NOTESID, FORECASTDATE FROM CONTNOTES WHERE NOTESID = ?");
mysqli_stmt_bind_param($rs_notes, "i", $_GET['NOTESID']);// bind parameters
mysqli_stmt_execute($rs_notes);// execute query
mysqli_stmt_bind_result($rs_notes, $NOTESID, $FORECASTDATE);// bind result variables

?>
<html>
<head>
    <meta charset="utf-8"/>
</head>

<body>

    <?php while (mysqli_stmt_fetch($rs_notes)) {?>

        <form class="prompts" action="" method="POST" enctype="multipart/form-data" name="editnoteform" id="editnoteform" onSubmit="">

            <input class="prompt" type="date" name="forecastdate" id="forecastdate" value="<?php if($FORECASTDATE <> NULL){echo date("Y-m-d",strtotime($FORECASTDATE));} ?>">

            <input type="hidden" name="notesid"  id="notesid" value="<?php echo $NOTESID; ?>">
            <input type="hidden" name="update" value="editnoteform">

            <input class="button" name="submit" id="submit" type="submit" value="Update">

        </form>

    <?php } ?>

</body>
</html>

<?php
mysqli_stmt_close($rs_notes);
mysqli_close ($conn);
?>

How is this an incorrect date value if the html field is a "date" type?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Richard Owens
  • 155
  • 16
  • 1
    `mysqli_stmt_bind_param($record_update, "si",` not `di` And make sure that `$_POST['forecastdate']` is in the format `yyyy-mm-dd` or `yyyy-mm-dd hh:ii:ss` – RiggsFolly Nov 18 '21 at 13:50
  • `"di"` `d` means `double` when binding params. https://www.php.net/manual/en/mysqli-stmt.bind-param.php – brombeer Nov 18 '21 at 13:50
  • 1
    https://www.php.net/manual/en/mysqli-stmt.bind-param.php and read the "type specification chars" table. – ADyson Nov 18 '21 at 13:52
  • `if the html field is a "date" type`...what's in the HTML is comlpetely irrelevant to your PHP code. When the data arrives in PHP via the $_POST data it's just a string (and there's nothing to indicate whether it came from a HTML date field, or anything else). Unless you actually need to do date-related calculations on it within the PHP (in which case you'd parse it to a DateTime) then you can just pass that string along to mySQL directly. And anyway, mysqli doesn't have a specific `date` data type. – ADyson Nov 18 '21 at 13:53
  • @brombeer very good point! I've amended this and it stores valid dates but now doesn't store invalid dates such as NULL.... grrrr. I'm now getting "Fatal error: Uncaught mysqli_sql_exception: Incorrect date value: '' for column....." – Richard Owens Nov 18 '21 at 13:59
  • @RiggsFolly Thank you. Also picked up by brombeer and a good catch. I've also commented back to them. The string binding type works well but I'm now getting problems with invalid dates and not sure how to correct this issue with NULL values.... – Richard Owens Nov 18 '21 at 14:00
  • @ADyson Thank you - fixed this issue which has led to another related issue as commented back to RiggsFolly and brombeer. – Richard Owens Nov 18 '21 at 14:01
  • 1
    Is your column set to be `nullable`? – brombeer Nov 18 '21 at 14:01
  • @brombeer Forgive my naivity. The mysql table field can be NULL. Is that what you're asking? I'f not, I'm not sure what you mean? – Richard Owens Nov 18 '21 at 14:04
  • 3
    `$forecastdate = 'NULL';` as `NULL` is a PHP value that is not the MySQL null – RiggsFolly Nov 18 '21 at 14:07
  • @RiggsFolly I'm trying to absorb this. I'd put $forecastdate = NULL; so not sure how else to save null back to the DB... or do I use something like "0000-00-00"? – Richard Owens Nov 18 '21 at 14:11
  • Your if statement can be simplified to `$forecastdate = $_POST['forecastdate'] ?? NULL;` but you don't seem to be using that variable in your `bind_param`. Please note that if you want to store the value NULL then you **should not** wrap it in quotes like the comments suggested. – Dharman Nov 18 '21 at 15:35
  • It's not clear why this thread has been closed , quoting a "similar question". The quoted thread is not similar so its a shame someone felt closing this thread was appropriate. – Richard Owens Nov 18 '21 at 15:39
  • FYI `"0000-00-00"` is not a valid date. Older MySQL servers had a loose mode set by default and they would convert invalid date string formats into either `"0000-00-00"` or `NULL` but that is incorrect. If you are using modern MySQL or MariaDB versions you should have the strict mode enabled that would not allow you to insert any other string. – Dharman Nov 18 '21 at 15:40
  • Why do you think the closure is incorrect? The problem you asked is "How to insert date using prepared statements" The answer is just like any other string. What's wrong? – Dharman Nov 18 '21 at 15:41
  • @dharman Thank you. I've used $forecastdate = empty($_POST['forecastdate']) ? '0000-00-00' : $_POST['forecastdate']; and the MariaDB seems to accept it. I'm doing some more testing now but this seems to have resolved the issue. – Richard Owens Nov 18 '21 at 15:41
  • Please do not use `'0000-00-00'`!!! Use `NULL` if your column is set to allow NULL values. – Dharman Nov 18 '21 at 15:42
  • @Dharman I've tried various methods and it will not accept a null irrespective of 'NULL' or NULL. – Richard Owens Nov 18 '21 at 15:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/239366/discussion-between-dharman-and-richard-owens). – Dharman Nov 18 '21 at 15:43

0 Answers0