PHP date()格式MySQL中插入datetime方法

时间:2021-05-26

当使用PHP在MySQL中编写查询时,它的适用性将基于MySQL本身进行检查。所以使用MySQL提供的默认日期和时间格式,即'YYYY-MM-DD'

例子:

ATE: YYYY-MM-DDExample: 2019-01-28 DATETIME: YYYY-MM-DD HH:MI:SSExample: 2019-01-28 23:50:30 TIMESTAMP: YYYY-MM-DD HH:MI:SSExample: 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_at1 2019-01-28 12:39:16

要从DATETIME值获取年,季度,月,周,日,小时,分钟和秒,请使用以下语句中显示的函数:
HOUR(@dt),MINUTE(@dt),SECOND(@dt) ),DAY(@dt),WEEK(@dt),MONTH(@dt),QUARTER(@dt),YEAR(@dt);

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章