ばかげているかもしれませんが、この関数を使用すると、入力に基づいて必要なページ数を計算し、そこから必要なページ数をカウントして返します。
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'] . "\"");