•   欢迎来到21NN网.
  •   请记住本站网址www.21nn.cn

MySQL中插进去datetime时的PHP date()花样【php教程】,MySQL,datetime,PHP date()

摘要: MySQL以'YYYY-MM-DDHH:MM:SS'花样检索并显现DATETIME值。日期只能存储此范例,但它能够与很多时候花样函数一同运用来变动并显现它。当运用PHP在MySQL中编写...
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.ki4.cn/course/list/29.html

《mysql教程》http://www.ki4.cn/course/list/51.html

以上就是MySQL中插进去datetime时的PHP date()花样的细致内容,更多请关注ki4网别的相干文章!

分享到:

发表评论

评论列表

还没有评论,快来说点什么吧~

公众号二维码

微信公众号