简体   繁体   中英

MySQL PHP - Fatal error, query fails on page but not PHPMyAdmin

I have a query containing a MySQL variable to produce a running total of a time value, and it works and produces results/rows in PHPMyAdmin, but as soon as I try it on my site it produces "Fatal error: Call to a member function fetch_assoc() on a non-object" . If anyone could help me identify the issue here it would be greatly appreciated.

Query used in PHPMyAdmin [works]:

SET @total_duration := 0;
SELECT sec_to_time(@total_duration := @total_duration + time_to_sec(duration)) AS cumulative_duration
FROM tbl_flights
ORDER BY tbl_flights.flight_id ASC

Query within PHP file [does not work]:

<?php

include('config.php');

$sql = "SET @total_duration := 0;
        SELECT sec_to_time(@total_duration := @total_duration + time_to_sec(duration)) AS cumulative_duration
        FROM tbl_flights
        ORDER BY tbl_flights.flight_id ASC";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {

    echo $row['cumulative_duration'];

}

?>

mysqli_query can only handle one query at a time. You have two options:

Break it apart into two queries:

$sql = "SELECT sec_to_time(@total_duration := @total_duration + time_to_sec(duration)) AS cumulative_duration
        FROM tbl_flights
        ORDER BY tbl_flights.flight_id ASC";
$conn->query("SET @total_duration := 0");
$result = $conn->query($sql);

Or use mysqli_multi_query:

$sql = "SET @total_duration := 0;
        SELECT sec_to_time(@total_duration := @total_duration + time_to_sec(duration)) AS cumulative_duration
        FROM tbl_flights
        ORDER BY tbl_flights.flight_id ASC";

$result = $conn->multi_query($sql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM