Going through threads from 2009-2022 it doesn’t look like there has been a real answer on getting a query to timeout in PHP from MySQL (5.6). The PDO timeout attribute is for the connecting, not the execution. We don’t want all queries to stop executing after X seconds so the global MySQL variable can’t be used for this. We also don’t want the PHP script to stop running because the query took too long so max execution time on PHP side is ruled out.
I’ve found the following possible approach:
$db->query('SET SESSION MAX_STATEMENT_TIME = 15000;');
run the query that may take longer than 15 seconds, then restore the MAX_STATEMENT_TIME
value with:
$db->query('SET SESSION MAX_STATEMENT_TIME = 0;');
Is there a better way to do this though? I would think in the past +10 years something has changed.
Irrelevant threads:
- Setting a connect timeout with PDO
- PHP PDO execute to abort when MySQL query taking more than X seconds?
- PHP’s PDO is ignoring the ATTR_TIMEOUT option for MySQL when server cannot be reached
- https://serverfault.com/questions/401828/how-to-automatically-kill-slow-mysql-queries-after-n-seconds
#4 is close but will not work with MySQL 5.6, statement timeouts are not allowed there. (e.g. MAX_EXECUTION_TIME = 1000
)