首页 > 开发 > PHP > 正文

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

2024-05-04 22:41:23
字体:
来源:转载
供稿:网友

当使用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            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表