Skip to content

Instantly share code, notes, and snippets.

@cspray
Last active December 28, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cspray/7433450 to your computer and use it in GitHub Desktop.
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.
<?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