Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.