你好,我正在研究一个函数,它应该返回一个数据库结果集以及查询检索数据所花费的时间。效果很好,但我不知道如何返回时间和结果集并使它们在视图中可用。感谢您的帮助。
我的代码如下所示:
public function getNumResults($term) {
/* Count query Execution */
$starttime = microtime(true);
$query = $this->con->prepare("SELECT COUNT(*) as total
FROM sites WHERE title LIKE :term
OR url LIKE :term
OR keywords LIKE :term
OR description LIKE :term");
$endtime = microtime(true);
/* Calculates total time taken */
$duration = $endtime - $starttime;
$searchTerm = "%". $term . "%";
$query->bindParam(":term", $searchTerm);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row["total"];
}
在视图中,我返回的结果集如下所示:
<div class="mainResultSection">
<?php
$resultsProvider = new SearchResultsProvider($con);
$numResults = $resultsProvider->getNumResults($term);
/* Not working */
$timeResults = $resultsProvider->getNumResults($term)->duration;
echo "<p class='resultsCount'>$numResults results found. In $timeResults <p>";
?>
</div>
你需要返回一个数组。 也许只是将其添加到$row
. 此外,您需要在查询之前获取开始时间,并在以下之后获取结束时间:
//other code
$starttime = microtime(true);
$query->execute();
$endtime = microtime(true);
$row = $query->fetch(PDO::FETCH_ASSOC);
$row["duration"] = $endtime - $starttime;
return $row;
或者对于您当前的代码,您可以将其添加到对象变量中:
$this->duration = $endtime - $starttime;
然后访问:
$timeResults = $resultsProvider->duration;
太缺乏经验了。我使用了另一个函数来获取持续时间。但给出的其他答案有很大帮助。谢谢,这是最终代码工作:
/* Time to get results */
public function getTimeResult($term){
$query = $this->con->prepare("SELECT COUNT(*) as total
FROM sites WHERE title LIKE :term
OR url LIKE :term
OR keywords LIKE :term
OR description LIKE :term"
);
$searchTerm = "%". $term . "%";
$query->bindParam(":term", $searchTerm);
$starttime = microtime(true);
$query->execute();
$endtime = microtime(true);
/* Calculates total time taken */
$duration = $endtime - $starttime;
return $duration;
}