Home >Database >Mysql Tutorial >How Can I Execute Multiple SQL Queries in a Single PHP Statement?

How Can I Execute Multiple SQL Queries in a Single PHP Statement?

DDD
DDDOriginal
2024-12-16 09:27:12186browse

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:

  • When working with fetch functions or row count functions, such as mysql_fetch_* or mysql_num_rows, only the results of the first query are accessible.
  • It is recommended to close the database connection with mysql_close($conn) after executing all queries to free up resources.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn