Last active
August 29, 2015 14:02
-
-
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
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 | |
/** | |
* <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