我正在尝试使用前面添加的php将某些值更新到数据库中。我试图添加的数据之一是日期值。尽管第一次添加值时,所有内容都正确添加。当我尝试更新日期值时,数据始终更改为0000-00-00。所以我有以下问题:
1)我犯了什么错误,日期没有正确更新?
2)如何将日期的格式更改为DD/MM/YYYY?
这是更新代码(我知道我有SQL注入的风险,但这不是我现在关心的问题):

<?php
 //DISPLAY A LIST OF ALL Files
$sql = "select * from news";
$result = mysqli_query($mydb, $sql) or die(mysqli_error($mydb));

if(mysqli_num_rows($result)>0){
?>

<table class="table table-striped" >
<thead>
<td><b>NewsID</b></td>
<td><b>Headline</b></td>
<td><b>Story</b></td>
<td><b>Date</b></td>
<td><b>Actions</b></td>
</thead>
<tbody>
<?php while($rows=mysqli_fetch_array($result)){
    $NewsID = $rows['NewsID'];
    $Headline = $rows['Headline'];
    $Story = $rows['Story'];
    $Date= $rows['Date'];
 ?>
  <tr>
  <form method="post" id="action" action="<?php $_SERVER['PHP_SELF']?>">
  <?php //if update button was pressed change all plain text to textfields to enable inline editing
     if (isset($_POST['preUpdate']) && $_POST['NewsID']==$NewsID) { ?>
        <td><?php echo $NewsID ?></td>
        <td><input type="text" name="Headline" value="<?php echo $Headline?>"></td>
        <td><input type="text"name="Story" value="<?php echo $Story?>"></td>
        <td><input type="date" name="Date" value="<?php echo $Date?>"></td>
        <td><input type="submit" name="update" value="Save"/></td>
        <?php }
else {  //These file will be displayed in plain text ?>
        <td><?php echo $NewsID; ?> </a></td>
        <td><?php echo $Headline; ?></td>
        <td><?php echo $Story; ?></td>
        <td><?php echo $Date; ?></td>
        <td><input type="submit" name="preUpdate" value="Update"/>
            <input type="submit" name="delete" value="delete"/></td>
        <?php } // end of if update button was pressed ?>
       <input type="hidden" name="NewsID" value="<?php echo $NewsID?>">

      </form>
 </tr>
     <?php } //end of while loop that displays courses ?>
        </tbody>
    </table>
<?php }

最佳答案

将表中日期的数据类型视为date
mysql中date的标准格式是YYYY-MM-DD,因此应该以相同的格式存储。您正在尝试以不同的格式插入,因此日期存储为0000-00-00。您可以使用strtotime()将其更改为所需的格式;
储存时

$date = date("Y-m-d",strtotime($_POST['date']));

显示时
echo date("required format",strtotime($date));

有关格式,请参见here

07-24 09:47
查看更多