如何显示PHP中MySQL查询的执行时间? [英] How do I display execution time of a MySQL query in PHP?
问题描述
我正在开发一个PHP应用程序,该应用程序在文本框中进行查询并返回分页的结果.作为应用程序的一部分,我想报告查询的运行时间.
I am working on a PHP application that takes queries in a text box and returns paginated results. As part of the application I want to report the running time of the query.
这是我到目前为止所做的.
Here is what I have done so far.
我首先通过直接在文本框中输入并运行脚本来启用概要分析,然后开始:
I started off by enabling profiling in by directly entering in the text box and running the script:
set global profiling = 1
使用提供的文本框输入以下查询:
Using the provided text box I enter the following query:
select @@profiling
并获得:
1
最后,我这样运行查询:
Finally, I run the query as so:
select * from log
但是,当我运行用于分析查询的命令时:
However, when I run the command for to profile the query:
show profiles
我没有收到任何结果,也没有任何内容显示在页面上.
I receive no result and no content displayed on the page.
由于在显示配置文件"命令之后没有看到任何表,这是否意味着权限不足,或者我错过了下一步?
Since I see no table after the command "show profiles" does this mean that there are not sufficient privileges or am I missing another step?
我遵循以下步骤:
请告知.
我的PHP代码如下:
<?php
if($_POST)
{
$db = new PDO('mysql:host=localhost;dbname=<dbname>;charset=utf8', 'user', 'pass');
$stmt = $db->prepare($_POST['query']);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$errmsg = $stmt->errorInfo()[2]; //Output the error message - Index 2 of the array
echo $errmsg;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Log</title>
</head>
<body>
<form method="post" id="queryform">
<div class="label">
<span class="label">Enter SQL Query</span>
</div>
<div class="input">
<input type="text" name="query" size="150" value="<?=$_POST['query']?>" />
</div>
</form>
<? if (isset($records)): ?>
<table border="1">
<? foreach($records as $record): ?>
<tr>
<? foreach($record as $colname => $value): ?>
<td>
<?=$value;?>
</td>
<? endforeach; ?>
</tr>
<? endforeach; ?>
</table>
<? endif; ?>
</body>
</html>
任何帮助将不胜感激.
推荐答案
这很有魅力!
$db->query('set profiling=1'); //optional if profiling is already enabled
$db->query($_POST['query']);
$stmt = $db->query('show profiles');
$db->query('set profiling=0'); //optional as well
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$errmsg = $stmt->errorInfo()[2]; //Output the error message
更新(以下内容在我当前的设置下适用于innodb)
$db->query('set profiling=1'); //optional if profiling is already enabled
$db->query($_POST['query']);
$res = $db->query('show profiles');
$records = $res->fetchAll(PDO::FETCH_ASSOC);
$duration = $records[0]['Duration']; // get the first record [0] and the Duration column ['Duration'] from the first record
来自phpmyadmin的(显示配置文件)的结果.
Result of (show profiles) from phpmyadmin.
Query_ID Duration Query
1 0.00010575 SELECT DATABASE()
取得实际PHP中最后一个查询的(绝对)执行时间(不包括网络延迟等)
这篇关于如何显示PHP中MySQL查询的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!