I want to run this long SQL query in PHP.
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
);
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = merchandise_count.merchandise_id;
Here's a quick explanation of what it does: First it creates a temporary table to store some selected data, then it uses the temporary table to INNER JOIN it with data in a permanent table.
I have already tried '$statement1;$statement2;' in PHP, but it gives syntax and access violation error but the given query works flawlessly in phpmyadmin.
I checked other similar posts like this and they suggest to use '$statement1;$statement2;' but it doesn't work for me. My server is running PHP 7. I'm using PHP PDO to connect to my database. Any help is appreciated.
I ran the following and it did work.
Notice I had to fix
merchandise_count.merchandise_idtoinfo.merchandise_idin your query, because you have no table reference tomerchandise_count.However, I would recommend you do not bother with multi-query. There's no benefit from concatenating multiple SQL statements in a single call. It's also not supported to use prepared statements when using multi-query, or to define stored routines like procedures, functions, or triggers.
Instead, execute the statements one at a time. Use
exec()if the statement has no result set and doesn't need to be prepared statements.As long as you use the same
$pdoconnection, you can reference temporary tables in subsequent queries.