Skip to content

Instantly share code, notes, and snippets.

@pedrosancao
Last active August 29, 2015 14:02
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 pedrosancao/2498ed85b3c1834c5bdd to your computer and use it in GitHub Desktop.
Save pedrosancao/2498ed85b3c1834c5bdd to your computer and use it in GitHub Desktop.
Searches all the columns names in a SQL query, works on wide range of fields including calculated fields
<?php
/**
* <p>Searches all the columns names in the given query, backticks are ignored</p>
* <p>Works on wide range of fields:</p>
* - column
* - column alias
* - column AS alias
* - table.column
* - table.column alias
* - table.column AS alias
* <p>including calculated fields e.g.:</p>
* - COUNT(table.column) alias
* - EXISTS (SELECT column FROM table.column2 SEPARATOR ';') alias
* - GROUP_CONCAT(table.column ORDER BY table.column2 SEPARATOR ';') alias
*
* @author Pedro Sanção <pedro@sancao.com.br>
* @license GNU General Public License version 2
* @param string $sql well formed SQL query
*/
function searchColumns($sql) {
$fromPos = 0;
$limit = substr_count($sql, 'FROM');
for ($i = 0; $i < $limit; $i++) {
$fromPos = strpos($sql, 'FROM', $fromPos + 1);
if(substr_count($sql, '(', 0, $fromPos) === substr_count($sql, ')', 0, $fromPos)) {
$sql = trim(substr($sql, 0, $fromPos));
break;
}
}
$matches = array();
preg_match_all('/(?<=^SELECT |, |\) )([a-z]+\.)?([a-z]+ )?(as )?([a-z]+)(?= ?,|$)/im', $sql, $matches);
return array_pop($matches);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment