Home >Backend Development >PHP Tutorial >How Can I Execute Multiple MySQL Queries in a Single PHP Statement?
Executing Multiple MySQL Queries in One Attempt
Executing multiple MySQL queries in a single attempt can be a convenient solution for specific use cases. In PHP, this task can be achieved using specific methods, each with its own advantages and limitations.
Option 1: Using mysql_multi_query in mysqli
The mysqli extension provides a function called mysql_multi_query that allows executing multiple queries in a single statement.
$link = mysqli_connect("localhost", "user", "password", "database"); $result = mysqli_multi_query($link, "SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; SELECT FOUND_ROWS();");
Option 2: PDO Multi-Query
PDO (PHP Data Objects) also supports executing multiple queries in a single statement using the PDO::query() method.
$pdo = new PDO("mysql:host=localhost;dbname=database", "user", "password"); $result = $pdo->query("SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; SELECT FOUND_ROWS();");
Handling Query Results
Once the multiple queries have been executed, you can handle each result set separately using the specific methods provided by the database driver you are using.
Additional Considerations:
The above is the detailed content of How Can I Execute Multiple MySQL Queries in a Single PHP Statement?. For more information, please follow other related articles on the PHP Chinese website!