0


I'm trying to insert a date into a table on my database. I currently this HTML code to insert the date :

<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="date" name="date">
<input type="submit" name="submit">
</form>
</body>
</html>

And this PHP code to process the request :

<?php
if(isset($_POST['submit'])) {
    $conn = new mysqli(MY_CONNECTION);
    $sql = "INSERT INTO my_table (date) VALUES (".$_POST['date'].")";
    $result = $conn->query($sql);
    if(!$result) {
        die("SQL Error : ".$sql."<br>Error : ".$conn->error);
    }
}
?>

My table only contains an ID column and a DATE column that is a DATE type.
When I submit my form, SQL executes correctly but when my values are stored in the database the result for DATE is '0000-00-00'. I didn't change anything in the date format of my database.
I tried with a print_r on my $_POST array end it prints out this :

Array ( [date] => 2017-04-04 [sell_Software_1] => Sell )

What am I doing wrong?
Thanks!

DamiToma
  • 921
  • 3
  • 9
  • 27
  • 1
    What is the format of `$_POST['date']`? You also are open to SQL injections. – chris85 Apr 06 '17 at 18:50
  • 2
    The date must enclosed in singe quotes `VALUES ('".$_POST['date'].")'"; . `. But better you use prepared statements – Jens Apr 06 '17 at 18:51
  • @chris85 I use to filter my data using FILTER_SANITIZE_MAGIC_QUOTES. Is this a valid solution? – DamiToma Apr 06 '17 at 18:52
  • 1
  • @Fred-ii- Which browsers do not support this input type? – DamiToma Apr 06 '17 at 18:54
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date - Firefox for one. – Funk Forty Niner Apr 06 '17 at 18:55
  • 1
    You should parameterize your query. I'm surprised anything `magic_quotes` is still around. `INSERT INTO my_table (date) VALUES (?)`. Prepare then then bind the `POST` value, and execute your query. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php – chris85 Apr 06 '17 at 18:55
  • @chris85 Thanks! – DamiToma Apr 06 '17 at 18:57
  • @Fred-ii- Do you know what happens if there are not supported input on a browser? Does it not show my input, or does it give me a strange value? – DamiToma Apr 06 '17 at 18:58
  • 2
    if you want it to be cross-browser, use a `text` type. You can also find yourself a datepicker that could also do the job but then you're going into JS territory. – Funk Forty Niner Apr 06 '17 at 18:59
  • @Hexadect See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date `browsers not supporting this type will display a simple text control` – chris85 Apr 06 '17 at 18:59
  • @Barmar I don't think this is a duplicate of the question you linked to; that is asking about quoting data for insertion, this is about date formatting. Hexadect: In order to ensure consistent data format, you should use ` – alanlittle Apr 06 '17 at 19:04
  • @alanlittle He's formatting his date correctly, the problem is he didn't put it in quotes. – Barmar Apr 06 '17 at 19:06

0 Answers0