gpt4 book ai didi

php - 在用户中止时终止 MySQL 查询

转载 作者:IT老高 更新时间:2023-10-29 00:06:21 27 4
gpt4 key购买 nike

从 PHP 运行长查询时,如果用户在浏览器中按下停止键,[如何]终止查询?

考虑到我无法调用任何其他 PHP 函数,因为 PHP 在等待 MySQL 时被阻塞。

此外,由于 session 锁定,我不能再向服务器发出任何请求(通过 Ajax)。

所以一个解决方案可能是:

  • 忽略用户中止
  • 在后台运行长查询并让 PHP 每 100 毫秒检查一次是否已完成
  • 从查询中获取 pid
  • 如果用户中止,则终止 pid
  • 否则完成后返回结果

我不知道该怎么做的两件事是:

  • 运行非阻塞(后台)查询
  • 获取查询的pid

最佳答案

对于那些有兴趣的人,这是我使用的:

<?php
// Connection to query on
$query_con = mysqli_connect($host, $user, $password, $name, $port);

// Connection to kill on
$kill_con = mysqli_connect($host, $user, $password, $name, $port);

// Start the query
$query_con->query($slow_query, MYSQLI_ASYNC);

// Get the PID
$thread_id = $query_con->thread_id;

// Ignore user abort so we can kill the query
ignore_user_abort(true);

do {
// Poll MySQL
$links = $errors = $reject = array($mysqli->mysqli);
$poll = mysqli_poll($links, $errors, $reject, 0, 500000);

// Check if the connection is aborted and the query was killed
if (connection_aborted() && mysqli_kill($kill_con, $thread_id)) {
die();
}
} while (!$poll);

// Not aborted, so do stuff with the result
$result = $link->reap_async_query();
if (is_object($result)) {
// Select
while ($row = $result->fetch_object()) {
var_dump($row);
}
} else {
// Insert/update/delete
var_dump($result);
}

关于php - 在用户中止时终止 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com