查询不返回任何记录,但phpmyadmin会返回

时间:2016-08-13 19:00:22

标签: php mysql sql phpmyadmin

我在查询数据库以查找结果时遇到问题。当我在phpmyadmin中输入查询时,它完美地运行。但是在php中执行完全相同的查询不会返回任何结果。

我已经在互联网上搜索了很长一段时间,但在任何地方我都觉得这种查询被认为是最好的答案。也许我错过了什么,你们可以帮助我。

查询:

SELECT current_consumption, current_delivery, UNIX_TIMESTAMP(timestamp) FROM energydata WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 HOUR);

PHP:

<?php
include "database.php";

$limit = (int)$_GET["limit"];

// Create connection
$conn = new mysqli($servername, $databaseUser, $databasePassword, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT current_consumption, current_delivery, UNIX_TIMESTAMP(timestamp) FROM energydata WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
$result = $conn->query($sql);

$json = array();

if ($result->num_rows > 0) {
    $columns = array(
        array(
            'id' => 'date',
            'label' => 'Date',
            'type' => 'datetime'),
        array(
            'id' => 'consumption',
            'label' => 'Consumption',
            'type' => 'number'),
        array(
            'id' => 'delivery',
            'label' => 'Delivery',
            'type' => 'number')
        );

    $rows = array();

    // output data of each row
    while($row = $result->fetch_assoc()) {
        $date = array();
        $date = date_parse($row['timestamp']);

        $currentRow = array(
            'c' => array(
                array(
                    'v' => 'Date('. $row['UNIX_TIMESTAMP(timestamp)'] .'000)'
                ),
                array(
                    'v' => $row['current_consumption']
                ),
                array(
                    'v' => $row['current_delivery']
                )
            )
        );

        array_push($rows, $currentRow);
    }

    $json = array(
        'cols' => $columns,
        'rows' => $rows);
}

echo json_encode($json);

1 个答案:

答案 0 :(得分:0)

这一定是一些数据问题。

您的代码在这里工作正常,只需进行一些小改动(首先查看var_dump)。

$conn = new mysqli("localhost:3308", "root", "", "testit");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "SELECT UNIX_TIMESTAMP(bill_date) FROM bills WHERE bill_date > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {   
   var_dump($row["UNIX_TIMESTAMP(bill_date)"]);
}
var_dump($result);

输出是:

string(10) "1489741452" 
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }