KILL MySQL queries using PHP if user close the bro

2019-04-07 12:32发布

问题:

My website is using onload AJAX. So when the user entering into a page 6 AJAX calls are executed parallel. In middle of the process if user close the browser or navigate to another page I wants to kill the queries.

Steps to achieve this:

1. Find the Next MySQL query execution ID(The connection identifier) and store it into a session.

http://dev.mysql.com/doc/refman/5.1/en/show-processlist.html

We need to identify this ID before execute the READ(select) query. Because PHP will execute line by line.

Problem

How do we identify the next connection identifier?

OR

How do we reserve the connection identifier and execute the query on specified identifier?

2. Execute the query in database.

3. If user aborted is identified then kill the MySQL query execution. We can detect the user aborted status in PHP using connection_aborted()/ ignore_user_abort() function.

Use this following command to terminate this query execution:

KILL ID

回答1:

step 1: Get thread id of the MySql connection

    $thread_id = mysqli_thread_id($link);

step 2: Use ignore_user_abort(); in code

step 3: Check if connection is closed. If yes then kill the thread as follows:

        if (connection_aborted() && mysqli_kill($connection_link, $thread_id)) {
           die();
        }

Check the accepted solution of this question.



回答2:

The following query also returns the current connection identifier

SELECT CONNECTION_ID();

After receiving this connection identifier we can execute our query on this identifier.