【问题标题】:Retrieve data from a specific sql command in php从 php 中的特定 sql 命令检索数据
【发布时间】:2017-05-03 16:28:30
【问题描述】:

我有一个包含一些温度数据和日期的数据库。要绘制数据,我需要将日期时间转换为 ISO8601。 我找到了选择正确数据并转换它们的命令:

SELECT DATE_FORMAT(`datelog`, '%Y-%m-%dT%TZ') AS date_formatted FROM `tempo` ORDER BY id ASC

在 phpmyadmin 中数据显示正确,但是当我使用相同的命令运行我的 php 脚本时,它会显示存储在数据库中的数据(例如:{"datelog":"2016-12-18 11:54: 11","唐尼":"16.937"})。我该如何改变呢?

<?php
//setting header to json
header('Content-Type: application/json');

//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '******');
define('DB_NAME', 'tempo');

//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = "SELECT DATE_FORMAT(`datelog`, \'%Y-%m-%dT%TZ\') AS date_formatted\n" . "FROM `tempo`\n" . "ORDER BY id ASC ";

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    它可以串联起来:

    $query = "SELECT DATE_FORMAT(`datelog`, \'%Y-%m-%dT%TZ\') AS date_formatted\n" . "FROM `tempo`\n" . "ORDER BY id ASC ";
    

    如果函数试试这个:

    $query = "SELECT DATE_FORMAT(`datelog`, \'%Y-%m-%dT%TZ\') AS date_formatted\n . " " . FROM `tempo`\n . " " . ORDER BY id ASC . ";
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2021-02-16
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2016-01-23
    相关资源
    最近更新 更多