/    Sign up×
Community /Pin to ProfileBookmark

bug in parsing SQL commands

Hello

I tried to write a function that takes a parameter content of an SQL file and executes the statements in it, one after the other.
Here is an example of such content

[code]
# Drop all the tables

DROP TABLE IF EXISTS `table1`;
DROP TABLE IF EXISTS `table2`;

# Create empty tables

CREATE TABLE `table1` (
`ID` TINYINT(1) unsigned NOT NULL,
`Param` varchar(255) default ”,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `table2` (
`ID` TINYINT(1) unsigned NOT NULL,
`Param` varchar(255) default ”,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table1` (`ID`, `Param`) VALUES (1, ‘ABC’);
INSERT INTO `table2` (`ID`, `Param`) VALUES (1, ‘abc’);
[/code]

Here is my function:

[code=php]
function runBatchOnConnection($connection, $batchContent) {
$commands = explode(‘;’, $batchContent);
foreach ($commands as $command) {
$command = trim($command);
if ($command == ”) {
continue;
}
$command = stripslashes($command);
$result = mysql_query($command, $connection);
if ($result === false) {
trigger_error(“Error in executing query: ” . $command . “rn” . mysql_error($connection), E_USER_ERROR);
exit;
}
}
}
[/code]

The problem with this function is that it fails on an SQL statement which contains a ‘;’. For example:

[code]
INSERT INTO `table2` (`ID`, `Param`) VALUES (2, ‘;’);
[/code]

Can anyone show me how it could be fixed?

regards

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@ShrineDesignsSep 24.2004 — it fails because you use ";" as a delimiter for explode()

try this:[code=php]$commands = preg_split("/;(r*)(n*)/im", $batchContent);[/code]
×

Success!

Help @jasongr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...