我有一个包含MySQL变量的查询来生成一个时间值的运行总计,它在PHPMyAdmin中工作并产生结果/行,但是一旦我在我的网站上尝试它就生成"Fatal error: Call to a member function fetch_assoc() on a non-object"
。如果有人能帮助我在这里找出问题,我们将不胜感激。
PHPMyAdmin中使用的查询[有效]:
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
在PHP文件中查询[不起作用]:
<?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'];
}
?>
答案 0 :(得分:3)
mysqli_query一次只能处理一个查询。您有两种选择:
将它分成两个查询:
$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);
或者使用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);