php-mysqlHow to set a timeout for MySQL query in PHP?
The mysqli_query()
function in PHP can be used to set a timeout for a MySQL query. The timeout
parameter of the function can be used to set the timeout value in seconds.
$mysqli = new mysqli("localhost", "user", "password", "database");
$query = "SELECT * FROM table";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT, MYSQLI_OPT_CONNECT_TIMEOUT, 10);
The output of the above code will be a mysqli_result
object if the query is successful, or FALSE
if the query times out.
Code explanation
$mysqli = new mysqli("localhost", "user", "password", "database");
: This line creates a newmysqli
object with the given parameters.$query = "SELECT * FROM table";
: This line sets the query to be executed.$result = $mysqli->query($query, MYSQLI_STORE_RESULT, MYSQLI_OPT_CONNECT_TIMEOUT, 10);
: This line executes the query with a timeout of 10 seconds.
Helpful links
More of Php Mysql
- How to create an SSL connection to MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to return multiple rows as an array in MySQL using PHP?
- How to get the error message for a MySQL query using PHP?
- How to run multiple queries in PHP and MySQL?
- How to prepare a statement in MySQL using PHP?
- How to join tables with PHP and MySQL?
- How to update to null value in MySQL using PHP?
- How to replace a string in MySQL using PHP?
- How to escape JSON in PHP and MySQL?
See more codes...