您好,我正在研究一个函数,该函数应该返回数据库结果集以及查询检索数据所用的时间。效果很好,但我不知道如何返回时间和结果集并使它们在视图中可用。感谢您的帮助。
我的代码如下:
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>
答案 0 :(得分:1)
您需要返回一个数组。也许只需将其添加到$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;
答案 1 :(得分:0)
经验不足。我使用另一个函数来获取持续时间。但是给出的其他答案很有帮助。谢谢,这里的最终代码有效:
/* 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;
}