Last active
December 28, 2015 03:09
-
-
Save cspray/7433450 to your computer and use it in GitHub Desktop.
A very rough implementation to convert an INSERT INTO SQL statement to an appropriate array structure for inserted values. There are caveats to the use of this function and full error handling has not yet been implemented.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function convertInsertIntoToArray($sql) { | |
$text = \explode(\PHP_EOL, $sql); | |
$data = array(); | |
if (!empty($text)) { | |
$firstLine = \preg_replace('/\s+$/', '', $text[0]); | |
if ($firstLine === 'INSERT INTO') { | |
if (\preg_match('/\(.+\)/', $text[1], $cols)) { | |
$cols = \explode(',', \preg_replace('/\(|\)|\s|\`/', '', $cols[0])); | |
for ($i = 3, $l = \count($text); $i < $l; $i++) { | |
$val = \rtrim(\preg_replace('/\(|\)|\s|\`|\;|\'/', '', $text[$i]), ','); | |
$vals = \explode(',', $val); | |
$record = array(); | |
for ($j = 0, $k = \count($cols); $j < $k; $j++) { | |
$record[$cols[$j]] = $vals[$j]; | |
} | |
$data[] = $record; | |
} | |
} | |
} | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment