简体   繁体   中英

I only getting Year that from HTML input type="date" to Database

this the code I used to get Date to my database and I getting the Year only to the database. what change I need to get dd/mm/yyyy to my Database

<?php
    $conn=mysqli_connect("localhost","root","","home_ac");
    if(mysqli_connect_error()) {
        die("Error While Connecting Database");
    }
    $date = ($_POST['date']);
    $query= "INSERT INTO `sample`(`id`, `date`, `currency`) VALUES (NULL,$date,'$date')";
        mysqli_query($conn, $query)

?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<form method="post">
    <input type="date" name="date" placeholder="Date">
    <input type="submit" value="ADD">
</form>
</body>
</html>

This example will display an input date box, ideally:

<label>Datetime:
<input type = "datetime"-local />
    (yyyy-mm-ddThh:mm, such as 2012-01-27T03:15)
</label>
if(isset($_POST['date'])){
$date = $_POST['date'];
 }

Also your query to the database should be formatted as such (assuming your ID is auto incremented):

 $query = "INSERT INTO tablename(date) 
 VALUES('{$date}')                            

Have your database formatted to accept the DATE format.

You need to make sure the date you are trying to insert is in the correct format. This is assuming

  • your user enters a date like mm/dd/yyyy or dd/mm/yyyy - MySQL wants yyyy-mm-dd
  • your date field is a date type, not datetime or timestamp

You can do this to convert:

$conn = mysqli_connect('localhost', 'root', '', 'home_ac');
$date = $_POST['date'];
$date = date("Y-m-d", strtotime($date));  //Would convert mm/dd/yyyy or dd/mm/yyyy or mm/dd/yy, etc. into yyyy-mm-dd for you.

if(mysqli_connect_error()) {
    die("Error While Connecting Database");
};

$query = "INSERT INTO `sample`(`id`, `date`) VALUES (NULL, '$date');";
mysqli_query($conn, $query);

Your initial query included a field, currency , that I did not include as you didn't have it in your html as a field a user would enter. I'm guessing you have a valid password for root (your connect didn't include it and no root password is a bad thing)

You should also make sure you are validating that your user is entering a valid date, etc.

You may want to reconsider your table layout as date is a MySQL reserved word . You can use it but you have to make sure to always enclose it with a backtick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM