Vah*_*ahe 2 php mysql pdo query-optimization
我正在开发一个PHP应用程序,它在文本框中接受查询并返回分页结果.作为应用程序的一部分,我想报告查询的运行时间.
这是我到目前为止所做的.
我开始通过直接进入文本框并运行脚本来启用性能分析:
set global profiling = 1
Run Code Online (Sandbox Code Playgroud)
使用提供的文本框我输入以下查询:
select @@profiling
Run Code Online (Sandbox Code Playgroud)
得到:
1
Run Code Online (Sandbox Code Playgroud)
最后,我运行查询:
select * from log
Run Code Online (Sandbox Code Playgroud)
但是,当我运行命令以分析查询时:
show profiles
Run Code Online (Sandbox Code Playgroud)
我没有收到任何结果,也没有在页面上显示任何内容.
因为我在命令"show profiles"之后看不到任何表,这意味着没有足够的权限或我错过了另一个步骤?
我按照以下程序:
请指教.
我的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>
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
这就像一个魅力!
$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
Run Code Online (Sandbox Code Playgroud)
更新(以下现在适用于我目前设置的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
Run Code Online (Sandbox Code Playgroud)
来自phpmyadmin的(显示配置文件)的结果.
Query_ID Duration Query
1 0.00010575 SELECT DATABASE()
Run Code Online (Sandbox Code Playgroud)
获取PHP中最后一个查询的实际(绝对)执行时间(不包括网络延迟等)
这个怎么样:
$start = microtime(true);
$stmt->execute();
$end = microtime(true);
echo "This query took " . ($end - $start) . " seconds.";
Run Code Online (Sandbox Code Playgroud)