PHP date()格式MySQL中插入datetime方法
程序员文章站
2023-11-26 14:07:40
当使用php在mysql中编写查询时,它的适用性将基于mysql本身进行检查。所以使用mysql提供的默认日期和时间格式,即'yyyy-mm-dd'
例子:
a...
当使用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);