当前位置:   article > 正文

php pdo mysql where,PHP PDO动态WHERE子句

php pdo构造器 where

I have a simple function that returns a count from a database table, based on some criteria.

function MyCount($strTable, $strCriteria) {

$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";

if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;

$results = mysql_query($strSQL, $objConn);

$row = mysql_fetch_array($results);

return $row[0];

}

Its very useful for quickly getting a value in 1 line of code, e.g:

$Users = MyCount("Users", "Deleted = 0");

However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):

$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");

$objQuery->bindParam(':table_name', $strTable);

$objQuery->bindParam(':criteria', $strCriteria);

I guess the obvious would be:

$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");

$objQuery->bindParam(':table_name', $strTable);

But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?

Thanks

解决方案

This line is the issue:

$objQuery->bindParam(':table_name', $strTable);

You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.

So you just build the query manually:

SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria

function my_count($strTable, $strCriteria, $objConn)

{

$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";

$objQuery=$objConn->query($sql);

$row =$objQuery->fetch();

return $row['TheCount'];

}

$Users = my_count("Users", "Deleted = 0", $objConn);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/139379
推荐阅读
相关标签
  

闽ICP备14008679号