mercredi 25 juin 2014

split sql statements in php on semicolons (but not inside quotes)


Vote count:

0




I have a system that is causing errors when users use a semicolon in a free format field. I have traced it down to a simple explode statement:



$array = explode( ";", $sql );


Because this line is in a subroutine that is called from all over the system I would like to replace this line with something that will split things properly, without breaking the rest of the system. I thought I was onto a winner with str_getcsv, but that isn't sophisticated enough either. Look at the following example



$sql = "BEGIN;INSERT INTO TABLE_A (a, b, c) VALUES('42', '12', '\'ab\'c; DEF');INSERT INTO TABLE_B (d, e, f) VALUES('42', '43', 'XYZ ;uvw');COMMIT;";

$array = str_getcsv($sql, ";", "'");
foreach( $array as $value ) {
echo $value . "<br><br>";
}


When I run this is outputs the following:



BEGIN


INSERT INTO TABLE_A (a, b, c) VALUES('42', '12', '\'ab\'c


DEF')


INSERT INTO TABLE_B (d, e, f) VALUES('42', '43', 'XYZ


uvw')


COMMIT



So it doesn't notice the semicolons are inside quotes. (As far as I can see the quoted strings from different places in the system are always in single quotes, but it is possible that at times they are double quotes, I am not sure about that.)


Can anyone tell me how to do this? I suspect I can do this with a very complicated regex, but this is over my head.



asked 48 secs ago






Aucun commentaire:

Enregistrer un commentaire