Created
January 25, 2016 04:11
-
-
Save slav123/29294ce1d86ba6602ad6 to your computer and use it in GitHub Desktop.
replace select ... part from mysql query with count
This file contains hidden or 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 | |
/** | |
* replace select in query | |
* | |
* @param string $query query to replace | |
* @param string $pkey primary key | |
* | |
* @return mixed|string | |
*/ | |
function count_row($query, $pkey) { | |
$query = str_replace("\n", " ", $query); | |
if (stripos($query, ' order by') !== false && preg_match("/SELECT\s(.+?)\sFROM.+(ORDER.+)/i", $query, $match)) { | |
array_shift($match); | |
return trim(str_replace($match, ['COUNT(`' . $pkey . '`) AS no', ''], $query)); | |
} | |
if (stripos($query, ' limit') !== false && preg_match("/SELECT\s(.+?)\sFROM.+(LIMIT.+)/i", $query, $match)) { | |
array_shift($match); | |
return trim(str_replace($match, ['COUNT(`' . $pkey . '`) AS no', ''], $query)); | |
} | |
return $query; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment