Home >Database >Mysql Tutorial >How Can I Execute Multiple SQL Queries in a Single PHP Statement?
Combining Multiple SQL Queries in a Single Statement with PHP
In PHP, executing multiple SQL queries in one statement can be achieved using the multi-query() function. This function allows you to chain multiple queries together and execute them as a single transaction.
Syntax:
$stmt = $conn->multi_query($query);
Example:
Consider the following multiple queries:
$query = "DELETE FROM active_codes WHERE sms_code ='$smsCode' AND code_type ='$id'"; $query .= "INSERT INTO used_codes (player, sms_code, code_type) VALUES ('$playerNick', '$smsCode', '$id')"; $query .= "INSERT INTO rewards (player, item_data, item_qty) VALUES ('$playerNick', '$itemData', '$itemQty')";
You can combine these queries into a single statement as follows:
$conn = new mysqli('localhost', 'username', 'password', 'database_name'); $stmt = $conn->multi_query($query);
Additional Considerations:
Note:
The example provided in the question references the deprecated mysql_* functions. It is recommended to use the mysqli or PDO extension instead for database connectivity in PHP.
The above is the detailed content of How Can I Execute Multiple SQL Queries in a Single PHP Statement?. For more information, please follow other related articles on the PHP Chinese website!