Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KILL MySQL queries using PHP if user close the browser or navigate from one page to other page

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

like image 570
Sundar Avatar asked Jan 10 '14 12:01

Sundar


People also ask

How do you end a query in PHP?

To stop a running query you should use the SQL command KILL QUERY processid .

How do I kill a MySQL query?

Run the following command: mysql> SELECT GROUP_CONCAT(CONCAT('KILL ',id,';') SEPARATOR ' ') FROM information_schema. processlist WHERE user <> 'system user'; This will kill all your MySQL queries.

How do I kill a query in phpMyAdmin?

In phpMyAdmin, go to home page > Status; you'll see a list of your MySQL processes and you have a Kill link for each of them.

How do I kill a process in MySQL workbench?

Here is the solution: Login to DB; Run a command show full processlist; to get the process id with status and query itself which causes the database hanging; Select the process id and run a command KILL <pid>; to kill that process.


2 Answers

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.

like image 174
Satish Gadhave Avatar answered Sep 28 '22 20:09

Satish Gadhave


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.

like image 42
Sundar Avatar answered Sep 28 '22 20:09

Sundar