Home >Database >Mysql Tutorial >Can Multiple SQL Queries Be Executed in a Single PHP Statement?

Can Multiple SQL Queries Be Executed in a Single PHP Statement?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 06:41:10244browse

Can Multiple SQL Queries Be Executed in a Single PHP Statement?

Executing Multiple SQL Queries in a Single Statement with PHP

Question:

Can multiple SQL queries be consolidated into a single statement in PHP?

Context:

The question relates to a scenario where multiple SQL queries are being executed separately:

$query = "DELETE FROM aktywne_kody WHERE kodsms ='$kodSMSgracza' AND typkodu ='$id'";
mysql_query($query) or die(mysql_error());

$query = "INSERT INTO uzyte_kody (gracz, kodsms, typkodu) VALUES ('$nickGracza', '$kodSMSgracza', '$id')";
mysql_query($query) or die("Błąd MySQL X04");

$query = "INSERT INTO do_odebrania (gracz, itemDATA, itemQTY) VALUES ('$nickGracza', '$itemDATA', '$itemQTY')";
mysql_query($query) or die("Błąd MySQL X05");

Answer:

Yes, it is possible to execute multiple SQL queries in a single statement in PHP using a specific parameter for mysql_connect().

Pass 65536 as the fifth parameter to mysql_connect():

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");

Once this parameter is set, multiple SQL queries can be executed in a single statement:

mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

It's important to note that when working with functions like mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement in the multiple queries will be processed. Functions like mysql_affected_rows can be used to retrieve the number of rows inserted or affected by the first query. However, functions like mysql_fetch_* will return values only for the first query and not for subsequent queries in the statement.

The above is the detailed content of Can Multiple SQL Queries Be Executed 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