Skip to content

Instantly share code, notes, and snippets.

@slav123
Created January 25, 2016 04:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slav123/29294ce1d86ba6602ad6 to your computer and use it in GitHub Desktop.
Save slav123/29294ce1d86ba6602ad6 to your computer and use it in GitHub Desktop.
replace select ... part from mysql query with count
<?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