I’m having an issue with a MySQL query when run in php. It works fine when I run it in PHPMyAdmin or SequelPro, but when copied into the PHP file it is meant to run in, it stops working.
The query is designed to take data from multiple tables that are linked with Primary Keys, and then put that data into corresponding identical tables. I know it’s an odd thing to do, but it needs to do it.
Query (as used in a PHP file) is as follows:
for($x = 0; $x < count($REQIDARRAY); $x++){
$sql="BEGIN;
INSERT INTO `Request`
SELECT NULL AS `RequestID`, `ModCode`, `RoomID`, `Students`, `Priority`, `Day`, `StartTime`, `Length`, `Semester`, `DateAdded`, `SpecialRequests`
FROM RequestTEMP
WHERE RequestTEMP.RequestID=\"".$REQIDARRAY[$x]."\";
INSERT INTO `Week`
SELECT `WeekNumber` , LAST_INSERT_ID() AS `RequestID`
FROM `WeekTEMP`
WHERE WeekTEMP.RequestID=\"".$REQIDARRAY[$x]."\"';
INSERT INTO `RequestFacilities`
SELECT LAST_INSERT_ID() AS `RequestID` , `FacilityID`
FROM `RequestFacilitiesTEMP`
WHERE RequestFacilitiesTEMP.RequestID=\"".$REQIDARRAY[$x]."\"';
DELETE FROM `RequestTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
DELETE FROM `RequestFacilitiesTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
DELETE FROM `WeekTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
COMMIT;";
$DB->Query('TransferMe' , $sql);
}
I have confirmed that $REQIDARRAY[$x] is returning correct values.
When running it in SequelPro, all that changes is that I would change
RequestID=\"".$REQIDARRAY[$x]."\"
to
'RequestID='123'
The error message in PHP is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘INSERT INTO Request SELECT NULL AS RequestID, ModCode, RoomID, `Student’ at line 2.
MySQL Version is 5.1.60.
I have no idea what is causing the problem, I’ve also tried hard coding values for RequestID into the PHP file and it still returns the same error.
Any help much appreciated!
The library you using is using
mysql_query()function, which cannot run multiple queries at once (as a protection against SQL injection).You need to run each of your queries with separate call to
$DB->Query(). Don’t worry, it will still be treated as a single transaction.Example:
Also: you might want to look at some more modern ways of accessing MySQL from PHP like ext/MySQLI (recommended by developers of MySQL) or PDO (favourited by majority of PHP coders)