我正在使用 PDO,用户应该可以选择停止他之前触发的请求。
例如,现在我单击生成报告,但是在请求之后我忘记选择一个使报告无用的字段。所以我需要取消请求,然后重新请求。
基本上,如何取消正在运行的 MYSQL 查询?
if (!isset($_POST['cancel_request'])) {
//query
}else{
//the user cancel the query
}
我知道我可以使用 kill 命令和 PID 进程,但这应该通过 PDO 运行,我不知道 PID 是什么。
最佳答案
这里的主要问题是在生成报告的异步请求和应该停止它的脚本之间共享 PID。
您可以使用以下方式获取您的 PID:
$stmt = $dbh->prepare("SELECT CONNECTION_ID()");
$stmt->execute();
$pid = $stmt->fetchColumn();
你可以使用类似 php-shared-memory 的东西在脚本之间创建共享变量。如果您的项目依赖项不使用 Composer,则此库有一个独立版本(1.5.0,here)。
实现示例:
<?php
if (!include __DIR__ . '/vendor/autoload.php')
{
die('You must set up the project dependencies.');
}
use Fuz\Component\SharedMemory\SharedMemory;
use Fuz\Component\SharedMemory\Storage\StorageFile;
// your intializations here
$storage = new StorageFile("/tmp/shared.{$user_id}.sync");
$shared = new SharedMemory($storage);
if (!isset($_POST['cancel_request']))
{
$stmt = $dbh->prepare("SELECT CONNECTION_ID()");
$stmt->execute();
$pid = $stmt->fetchColumn();
$shared->pid = $pid;
// your long query here
$shared->destroyStorage();
}
else
{
// kills pid
$pid = $shared->pid;
if (!is_null($pid))
{
$dbh->exec("KILL {$pid}");
}
}
关于mysql - 通过 pdo 停止查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719803/