简体   繁体   English

用PHP修改SQL SELECT语句

[英]Modify SQL SELECT statement with PHP

How best to alter a SQL SELECT statment's field list to a COUNT(*) using PHP? 如何最好地使用PHP将SQL SELECT语句的字段列表更改为COUNT(*)?

eg 例如

SELECT blah, blah, blah FROM tbl_blah WHERE blah; SELECT等等,等等,从tbl_blah那里等等;

to

SELECT COUNT(*) FROM tbl_blah WHERE blah 从tbl_blah选择COUNT(*)等等

I have considered mysql_num_rows... but I am pretty sure it would be more efficient to edit the statement. 我考虑过mysql_num_rows ...,但是我敢肯定,编辑该语句会更有效。 I am guessing it could be solved with a regex expression... :S 我猜它可以用正则表达式来解决...:S

The best thing would be to store the various pieces in separate variables and then call a function to coalesce them: 最好的办法是将各个部分存储在单独的变量中,然后调用一个函数来合并它们:

function makeSQL($fields, $tables, $conditions='')
{
  $sql = "SELECT $fields FROM $tables";
  if ($conditions != '')
  {
    $sql .= " WHERE $conditions";
  }
  return $sql;
}

That way you can call it with the proper fields one time, then COUNT(*) the next. 这样,您可以一次使用适当的字段来调用它,然后一次使用COUNT(*)来调用它。

You can do this using preg_replace() : 您可以使用preg_replace()进行此操作:

<?php
$sql = "SELECT blah, blah, blah FROM tbl_blah WHERE blah;";

$newSql = preg_replace(
    "/^SELECT (.*) FROM (.*)$/",
    "SELECT COUNT(*) FROM $2",
    $sql);

echo $newSql;
// SELECT COUNT(*) FROM tbl_blah WHERE blah;
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM