Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

php - Date not being sent over to mysql

I have looked everywhere, but I can't seem to find the correct code. I have an html form take in a date from the user using the "date" input.

index.html:

<form name="myform" action="process.php" method="POST">
     Date: <input type="date" name="date"><br>
     <input type="submit" value="Submit">
</form>

Process.php:

$link=mysqli_connect("my.sql.server", "username", "psswd", "database_name")
$date = $_POST['date'];
mysqli_query($link,"INSERT INTO visit_exclude_dates (date) VALUES (CAST $date AS DATE)");

the value of $date when it comes out of the form is in the yyyy-mm-dd format, and I am able to successfully write to the database. My problem is that when I read the database, the date is being shown as 0000-00-00. So I assume that the problem is with this line:

mysqli_query($link,"INSERT INTO visit_exclude_dates (date) VALUES (CAST $date AS DATE)");

EDIT: I would like to note that visit_exclude_dates is the name of my table

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try adding ticks around the date field in your query. Provided you're SURE the input is Y-m-d format, It'll most likely fix your issue:

$date = date("Y-m-d", strtotime($_POST['date']));
$result = mysqli_query($link,"INSERT INTO visit_exclude_dates (date) VALUES ('{$date}')");

if(!$result) {
    echo "Error: " . $link->error);
    die();
}

$result->close();
$link->close();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...