I wrote a database migration PHP script, that loops a list of SQL files and executes their content. It should help to automate the project setupd and updates. Now I'm getting errors like this:
mapCoursesToSport.sql: 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 'DELIMITER |
DROP PROCEDURE IF EXISTS mapCoursesToSport|
CREATE PROCEDURE mapCo' at line 1
I was getting the same error when I was passing to the script a file with a view definition, that also was using DELIMITER
s. Then I found the workaround just to remove the delimiters from the SQL file. And it worked. But now it's not an option, since stored procedures really need delimiter definitions.
So, how can I define MySQL stored procedures from PHP? (Or maybe morre generally: How should this SDELIMITER
be handeled?)
You can use native PHP function mysqli::query
and mysqli::prepare
alternatively to create stored procedure:
http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Using mysqli::multi_query also works but is a bit more tricky to handle since you might need to count the number of query to execute upfront before executing them one by one (provided the final query delimiter is optional, counting the queries can be tedious)
http://php.net/manual/en/mysqli.multi-query.php
<?php
// Using mysqli extension below in object-oriented mode
// after having executing queries
// with mysqli::multi_query
do {
$queryResult = $mysqli->use_result();
unset($results);
while ($result = $queryResult->fetch_array(MYSQLI_ASSOC)) {
$results[] = $result;
}
$queryResult->close();
if ($mysqli->more_results()) {
$mysqli->next_result();
}
$queryCount--;
} while ($queryCount > 0);
P.S.: The reason I'm not using mysqli:more_results
nor mysqli:next_result
as loop statement is that some query might be properly executed without returning any result. In such case, we don't want to break the loop before all queries have been executed.