Skip to content

Instantly share code, notes, and snippets.

@karllindmark
Created December 15, 2016 10:09
Show Gist options
  • Save karllindmark/e55ee0447f7737b9a8b550cf412add2f to your computer and use it in GitHub Desktop.
Save karllindmark/e55ee0447f7737b9a8b550cf412add2f to your computer and use it in GitHub Desktop.
Small script to parse an SQL query into an associative array
<?php
function parseQueryToArray($query) {
$twoWordChunks = array('GROUP', 'ORDER');
$twoWordChunk = '';
$joinChunks = array('LEFT', 'RIGHT', 'INNER', 'OUTER');
$joinChunk = '';
$out = array(
'SELECT' => null,
'FROM' => null,
'JOIN' => null,
'WHERE' => null,
'GROUP BY' => null,
'ORDER BY' => null,
'HAVING' => null,
'LIMIT' => null
);
$tempKey = '';
$tempValues = '';
$isJoin = false;
$chunks = explode(' ', $query);
foreach ($chunks as $chunk) {
if (in_array($chunk, $twoWordChunks)) {
$twoWordChunk = $chunk;
continue;
}
if (in_array($chunk, $joinChunks)) {
$joinChunk = $chunk;
continue;
}
if ($twoWordChunk) {
$chunk = $twoWordChunk . ' ' . $chunk;
$twoWordChunk = '';
}
if (array_key_exists($chunk, $out)) {
if ($tempKey && $tempValues) {
if (!$out[$tempKey]) {
$out[$tempKey] = $isJoin ? array() : '';
}
if ($isJoin) {
$out[$tempKey][] = implode(' ', $tempValues);
} else {
$out[$tempKey] .= implode(' ', $tempValues);
}
}
$tempKey = $chunk;
$tempValues = array();
$isJoin = $tempKey == 'JOIN' ? 1 : 0;
continue;
} else {
if ($joinChunk) {
$chunk = $joinChunk . ' ' . $tempKey . ' ' . $chunk;
$joinChunk = '';
}
$tempValues[] = $chunk;
}
}
if (!$out[$tempKey]) {
$out[$tempKey] = $isJoin ? array() : '';
}
if ($isJoin) {
$out[$tempKey][] = implode(' ', $tempValues);
} else {
$out[$tempKey] .= implode(' ', $tempValues);
}
return $out;
}
function injectSelectAndJoinIntoQuery($query, $selectToAdd, $joinToAdd) {
$queryArray = parseQueryToArray($query);
$out = array();
$out[] = 'SELECT ' . implode(',', $queryArray['SELECT']) . ' ' . $selectToAdd;
$out[] = 'FROM ' . implode(' ', $queryArray['FROM']);
if (count($queryArray['JOIN'])) $out[] = implode(' ', $out['JOIN']) . ' ' . $joinToAdd;
if ($queryArray['WHERE']) $out[] = 'WHERE ' . $queryArray['WHERE'];
if ($queryArray['GROUP BY']) $out[] = 'GROUP BY ' . $queryArray['GROUP BY'];
if ($queryArray['ORDER BY']) $out[] = 'ORDER BY ' . $queryArray['ORDER BY'];
if ($queryArray['HAVING']) $out[] = 'HAVING ' . $queryArray['HAVING'];
if ($queryArray['LIMIT']) $out[] = 'LIMIT ' . $queryArray['LIMIT'];
return implode(' ', $out);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment