MySQL以'YYYY-MM-DD HH:MM:SS'格式检索并显示DATETIME值。日期只能存储此类型,但它可以与许多时间格式函数一起使用来更改并显示它。
当使用PHP在MySQL中编写查询时,它的适用性将基于MySQL本身进行检查。所以使用MySQL提供的默认日期和时间格式,即'YYYY-MM-DD'
例子:
ATE: YYYY-MM-DD Example: 2019-01-28 DATETIME: YYYY-MM-DD HH:MI:SS Example: 2019-01-28 23:50:30 TIMESTAMP: YYYY-MM-DD HH:MI:SS Example: 2019-01-28 23:50:30 YEAR: YYYY or YY
用于创建DataBase的MySQL查询:
CREATE DATABASE Date_time_example;
示例1:用于创建数据库和表的PHP程序
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // 创建连接 $conn = mysqli_connect( $servername, $username, $password, $dbname ); // 检查连接 if ( !$conn ) { die("Connection failed: " . mysqli_connect_error()); } // 创建表的SQL查询 $sql = "CREATE TABLE date_test ( id INT AUTO_INCREMENT PRIMARY KEY, created_at DATETIME )"; if (mysqli_query($conn, $sql)) { echo "Table date_test created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } // 关闭连接 mysqli_close($conn);
输出:
Table date_test created successfully
示例2:将日期插入表中的PHP程序。
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // 创建连接 $conn = mysqli_connect( $servername, $username, $password, $dbname ); // 检查连接 if ( !$conn ) { die("Connection failed: " . mysqli_connect_error()); } // 用于向表中插入数据的SQL查询 $sql = "INSERT INTO date_test( created_at ) VALUES( '2019-01-28 12:39:16' );"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn);
输出:
New record created successfully
示例3:此示例用于显示在2019-01-28上创建的行。使用以下查询显示结果。created_at列不仅包含日期,还包含时间。所以它会显示错误信息。
SELECT * FROM date_test WHERE DATE( created_at ) = '2019-01-28';
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; //创建连接 $conn = mysqli_connect( $servername, $username, $password, $dbname ); // 检查连接 if ( !$conn ) { die("Connection failed: " . mysqli_connect_error()); } //SQL查询 $sql = "SELECT * FROM date_test WHERE DATE(created_at) = '2019-01-28'"; $result = mysqli_query( $conn, $sql ); if ($result) { echo $result; //打印查询结果 } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn);
输出:
id created_at 1 2019-01-28 12:39:16
要从DATETIME值获取年,季度,月,周,日,小时,分钟和秒,请使用以下语句中显示的函数:
HOUR(@dt),MINUTE(@dt),SECOND(@dt) ),DAY(@dt),WEEK(@dt),MONTH(@dt),QUARTER(@dt),YEAR(@dt);
推荐参考学习:
《PHP教程》http://www.php.cn/course/list/29.html
《mysql教程》http://www.php.cn/course/list/51.html
以上是MySQL中插入datetime时的PHP date()格式的详细内容。更多信息请关注PHP中文网其他相关文章!