我可能很愚蠢,但我有这个函数,它根据输入计算必要的页数,从中计算需要多少页并返回它。
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'] . "\"");