【发布时间】:2020-06-19 00:29:24
【问题描述】:
所以我正在创建一个非常简单的表单,我想在其中使用 PHP 将 HTML 表单中的数据添加到 MySQL 数据库中。不幸的是,输入 type="date" 标签给我的格式是这样的:,但 MySQL 需要的是这样的:。我已经搜索了很多在线资源以寻找解决方案,但似乎每个人都说格式无法更改。我不想更改格式,我只想能够将它们添加到数据库中。如果相关,这里是完整的 HTML/PHP 脚本:
store.html:
<!DOCTYPE html>
<html>
<head>
<title>Progress</title>
</head>
<body>
<form action="store.php" method="get">
Customer Name<input type="text" name="cname"><br>
Purchase order date<input type="date" id="podate"/><br>
<label for="yn">Work started?</label>
<select id="yn" name="yn">
<option value="yes">Yes</option>
<option value="no">No</option>
</select><br>
<label for="ifno">(If above selected is no)Reason for delay?</label>
<select id="ifno" name="ifno">
<option value="nodelay">No delay</option>
<option value="dipl">Delay from DIPL</option>
<option value="customer">Delay from customer</option>
</select><br>
Tentative start date<input type="date" name="tentdate"><br>
<label for="progress">Progress</label>
<select id="progress" name="progress">
<option value="started">Just Started</option>
<option value="almost">Almost Finished</option>
</select><br>
<input type="submit" name="sub" value="Submit">
</form>
</body>
</html>
store.php
<?php
include 'config.php';
$cname=$_GET['cname'];
$podate=$_GET['podate'];
$started=$_GET['yn'];
$reason=$_GET['ifno'];
$tentdate=$_GET['tentdate'];
$progress=$_GET['progress'];
if($cname=="" || $podate==""||$started=="" || $reason==""||$tentdate=""||$progress=""){
$message="All fields must be filled";
echo "<script type='text/javascript'>alert('$message');
window.location.href='store.html';</script>";
}
else{
$sql = "INSERT INTO info (cname, podate, started, reason, tentdate, progress) VALUES ('$cname', '$podate', '$started', '$reason', '$tentdate', '$progress')";
if (mysqli_query($conn, $sql)) {
//echo "New record created successfully";
header('Location: store.html');
} else {
$message="Something went wrong. Please try again.";
echo "<script type='text/javascript'>alert('$message');
window.location.href='store.html';</script>";
}
}
mysqli_close($conn);
?>
我的问题是 HTML 和 MySQL 格式不匹配,这使我无法将其存储到数据库中。我也尝试在插入语句中使用 DATE_FORMAT() 但后来了解到它可以用于显示但不能用于插入。
谢谢。
【问题讨论】:
-
MySQL
date字段 are 的形式为Y-m-d(它是 ANSI SQL 标准格式)只是 convert 你从 HTML 中得到的 - 这很漂亮你能做的很多。 请勿将日期作为VARCHAR(或类似)字段存储在数据库中,否则您将无法在其上使用任何本机日期函数(因为它不是@987654331 @字段)。