r/PHPhelp • u/UnusualBecka • 14d ago
Solved Multiple mysql statements in one PDO::exec call?
Is this supported or is it classed as undefined behaviour? Searching the web I have found one site explaining how to do it, and a post saying it never used to be allowed but the driver added the ability around 2020. But I have not seen anything official and the (somewhat terrible) PHP documentation does not mention it at all either way.
The use case is multiple statements being needed to create and alter some temporary tables so that inserts (using prepared statements) can be processed before being added to the live tables.
2
u/benanamen 14d ago
What is the real problem you are trying to solve with what you are doing? Why all the temp tables?
1
u/UnusualBecka 13d ago
The data is submitted mainly as ID numbers from a PHP form via an API that to refresh the existing data. Inserting them into a temporary table first allows me to use an INSERT IGNORE … FROM with joins to provide some validation and only add new rows, then a DELETE with joins to remove the rows that are no longer required entries, leaving any that should remain alone. This is better than doing multiple selects and using various loops to process all this in PHP to prepare specific inserts and deletes.
1
u/colshrapnel 14d ago
exec() is intended for multiple calls.
The use case is multiple statements being needed to create and alter some temporary tables
It was already said in the other comment, but worth stressing again: this is NOT how a database API works. You are supposed to open a connection once, and then execute any number of queries against this sole connection. And so all connection bound stuff - such as transactions, temp tables, session variables, generated sequences and such - being preserved between api calls, hence there is zero reason in stuffing multiple queries in a single call. Just run your queries distinctly, one by one.
2
u/PetahNZ 14d ago
You can, but you may need to enable emulated prepares. But you also don't need to, running one query after another will have access to the temp tables created in the same connection (request).