【发布时间】:2016-10-06 05:40:53
【问题描述】:
我创建了一个使用 php 和 mysqli 的网页,我可以在其中发送和编辑 MySQL 条目而不会出错。条目有标题和日期。当我尝试更改为 NULL 的日期时,就会出现问题。
- 创建一个带日期的条目:Works
- 创建不带日期的条目:有效
- 编辑带有日期的条目:有效
- 编辑日期为 NULL 的条目:有效
- 将日期为 NULL 的条目编辑为现有日期:(不起作用)
我已经尝试并测试了一些东西,我可以假设问题是当 PHP 生成表单时,“日”、“月”和“年”输入为空白/空。
也无法理解为什么创建条目的表单(完全相同但开头所有输入均为空白)在每种情况下都有效。
这就是我生成表单的方式:
$mysqli->set_charset('Latin1');
$id=$_POST["id"];
$res = $mysqli->query("SELECT * FROM `list` WHERE `id`=$id");
while($row = $res->fetch_assoc()) {
if ($row["fecha"]==NULL) {$day="";$month="";$year="";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "
<div class='home'>
<form accept-charset='Latin1' method='post' action='http://mypage.com/?opt=list&f=view'>
<input type='text' value='".$row['title']."' name='title' id='title' required><br>
<input type='number' value=".$day." name='day' id='day' min='1' max='31' placeholder='day'>
<input type='number' value=".$month." name='month' id='month' min='1' max='12' placeholder='month'>
<input type='number' value=".$year." name='year' id='year' placeholder='year'>
<input style='display:none;' type='number' value=".$id." name='id' id='id' placeholder='id'>
<input type='button' id='datepicker'><br>
<input type='submit' name='edit' value='Update'>
</form>
</div>";
};
这就是我提交时发生的情况:
$edit=$_POST["edit"];
if ($edit) {
$id=$_POST["id"];
$title=$_POST["title"];
if (empty($_POST["year"])&&empty($_POST["month"])&&empty($_POST["day"])){
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=(NULL) WHERE `id` = $id;");
}else{
$date=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=('$date') WHERE `id` = $id;");
};
print ("Entry updated to ".$date); //When it doesn't works nothing appears in $date
};
我不知道为什么它在“日”、“月”和“年”输入一开始为空时不起作用。
PS。这是一个解决方案(当日期为 NULL 时给出值,然后在生成表单时清除它们),但我仍然不知道输入有什么问题:
...
if ($row["fecha"]==NULL) {$day="0";$month="0";$year="0";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "...";
if ($row["fecha"]==NULL){echo "<script>document.getElementById('day').value='';document.getElementById('month').value='';document.getElementById('year').value='';</script>";
...
感谢任何帮助。
【问题讨论】:
-
尽量让空($_POST["year"]), not $_POST["year"]==null, day and month
-
您可以使用此代码进行 SQL 注入。您应该使用参数化查询,因为您的驱动程序支持它们。
-
你在那里提交绝对错误。您只是假设查询将始终成功。不好的假设。始终假设失败:检查失败,然后将成功视为惊喜。从技术上讲,“0000-00-00”是一个错误条件。如果要保存一个显示“未知日期”的值,请使用 sql
null。
标签: php mysql forms post mysqli