PHP PDO dynamic WHERE clause

瘦欲@ 提交于 2019-12-24 08:30:36

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/25697050/php-pdo-dynamic-where-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!