1

我可能很愚蠢,但我有这个函数,它根据输入计算必要的页数,从中计算需要多少页并返回它。

function get_total_pages($field, $table, $page_size = 20, $where_something = "", $equals_something = ""){
    global $dbh;
    try {
        if(empty($where_something)){
        // I deleted irrelevant code here
        }
        elseif(!empty($where_something) && !empty($equals_something)){
            $count_query = $dbh->prepare("SELECT COUNT(:field) FROM :table WHERE :where=:equals");
            $count_query->bindParam(":field", $field);
            $count_query->bindParam(":table", $table);
            $count_query->bindParam(":where", $where_something);
            $count_query->bindParam(":equals", $equals_something);
            $count_query->execute();
            $count = $count_query->fetch();
            $total_records = $count[0];                 // calculating number of records in history table
            $total_pages = ceil($total_records / $page_size);   // calculating number of pages necessary
            return $total_pages;
        }
        return false;
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }

我称之为
$total_pages = get_total_pages("username", "comments", $page_size, "username", $_GET['user']);

这是我得到的错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''comments' WHERE 'username'='redbot'' at line 1

但是,如果我将所有函数的代码换成更简单的 query() 而不是准备好的语句,它就可以工作,只要我在用户名后面加上引号:

function get_total_pages($field, $table, $page_size = 20, $where_something = "", $equals_something = ""){
    global $dbh;
    try {
        if(empty){
          //   irrelevant code
        }
        elseif(!empty($where_something) && !empty($equals_something)){
            $count_query = $dbh->query("SELECT COUNT({$field}) FROM {$table} WHERE {$where_something}={$equals_something}");
            $count = $count_query->fetch();
            $total_records = $count[0];                 // calculating number of records in history table
            $total_pages = ceil($total_records / $page_size);   // calculating number of pages necessary
            return $total_pages;
        }
        return false;
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}

$total_pages = get_total_pages("username", "comments", $page_size, "username", "\"" . $_GET['user'] . "\"");

4

2 回答 2

1

不能在准备好的语句中使用动态字段和表名称。

您必须自己检查它们(理想情况下,根据现有和允许的表和列名称的白名单)并自己将它们放入查询字符串中。

以下是一些代码片段,展示了如何执行此操作。

于 2013-01-28T10:10:43.197 回答
0

你不能用占位符定义列名,也看看bindParam和之间的区别bindValue

通常,参数仅在数据操作语言 (DML) 语句中合法,在数据定义语言 (DDL) 语句中不合法。

于 2013-01-28T10:11:27.273 回答