发布日期格式并从数据库中选择日期格式

时间:2016-06-02 09:41:51

标签: php mysql sql

我有一个文本框,以格式显示当前日期:d-m-Y

<input type="text" name="date" class="form-control" value="<?php echo date('d-m-Y');?>"/>

当我保存时,日期将写入我的数据库,如:Y-m-d。例如:当前日期是:02-06-2016。我的脚本将其写入数据库:2002-06-16。

我使用以下代码将数据保存到我的数据库:

<?php
 session_start(); 

 $correct = true;

 $date = $_POST['date'] ;

 if($correct){
  $db = new PDO('mysql:host=localhost;dbname=db', 'root', '');

  $query = "INSERT INTO table(date) VALUES (?)";
  $stmt = $db->prepare($query);
  $stmt->execute(array($date));

  header('Location: ./index.php');  
 }
 else
 {
  echo "Error";
 }
?>

我需要在代码中更改内容,以便发布如下:2016-06-02 Y-m-d或02-06-2016 d-m-Y

如果无法d-m-Y,如何在我的php脚本中显示数据库中Y-m-d所写的数据显示为格式d-m-Y

修改

选择我使用的日期:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";

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

$result = $conn->query($sql);

if ($result->num_rows > 0) {

     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<td>" . $row["id"]. "</td>";
                      echo "<td>" . $row["date"]. "</td>";
     }                   
} else {
                      echo "<p> </p>";
}

$conn->close();

?>  

1 个答案:

答案 0 :(得分:2)

$date = $_POST['date'] ;

$date = date("Y-m-d",strtotime($date));

$_POST['date']格式转换Y-m-d

要在HTML页面中以Y-m-d格式显示日期,请再次将其转换为

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

OR

echo date("d-m-Y",strtotime($row['date']));

[注意:我假设您的获取数组为$row,列为date。]

有关详细信息,请查看strtotime - php manual

更新代码(编辑问题时)

$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "<td>" . $row["id"]. "</td>";
    echo "<td>" . date("d-m-Y",strtotime($row['date'])). "</td>";
  }                   
} else {
  echo "<p> </p>";
}

$conn->close();