2013-10-08 58 views
1

我遇到了分頁問題。我已經儘可能地進行了調試,看起來SELECT查詢和執行有問題。如果我取出分頁部分,查詢將執行並顯示長表中的所有條目。我嘗試執行一個數組,bindValue和bindParam,但沒有任何工作,任何人都可以看到我失蹤?PHP OOP分頁

function showEmployees() { 
    $count = $this->dbh->query("SELECT * FROM employee_info"); 
    $count->rowCount(); 
    $count = $count->rowCount(); 

    // if ($count > 0) { 
    // echo "The total amount of employees is " . $count; 
    // } else { 
    // echo "There are no records in this table."; 
    // } 

    $page_rows = 10; 
    $last_page = ceil($count/$page_rows); 

    echo $last_page; 

    if ($last_page < 1) { 
    $last_page = 1; 
    } 

    $page_num = 10; 

    if (isset($_GET['pn'])) { 
    $page_num = preg_replace('#[^0-9]#', '', $_GET['pn']); 
    } 

    if ($page_num < 1) { 
    $page_num = 1; 
    } elseif ($page_num > $last_page) { 
    $page_num = $last_page; 
    } 

    $limit = 'LIMIT ' .($page_num -1) * $page_rows .', '. $page_rows;  

    $query = $this->dbh->prepare("SELECT * FROM employee_info ORDER BY employee_id DESC :page_limit"); 
    $query->bindParam(':page_limit', $limit); 
    $query->execute(); 


    $t = "<table name='displayEmployees' border='1' >"; 
    $t .="<tr>"; 
    $t .= "<th>Employee ID</th>"; 
    $t .= "<th>First Name</th>"; 
    $t .= "<th>Last Name</th>";    
    $t .= "</tr>"; 

    while($u = $query->fetch(PDO::FETCH_ASSOC)) { 
    $t .="<tr>"; 
    $t .= "<td>{$u['employee_id']}</td>"; 
    $t .= "<td>{$u['first_name']}</td>"; 
    $t .= "<td>{$u['last_name']}</td>"; 
    $t .="</tr>"; 
    } 

    $t .="</table>"; 

    return $t; 
}  

回答

0

您不能將關鍵字作爲您的預準備語句的參數。你需要做到這一點:

$limit = 'LIMIT ' .($page_num -1) * $page_rows .', '. $page_rows;  
$query = "SELECT * FROM employee_info ORDER BY employee_id DESC ".$limit; 
$query->query($query); 

注:因爲這些參數已通過你的腳本消毒你可以信任他們,所以準備好的聲明的利益在這種情況下,主要是丟失。

+0

感謝邁克,我明白你在說什麼,並欣賞它,由於注射的偏執我有這麼多爲我準備做不假思索所有發言的習慣,但你是正確的,在這種情況下,這是多餘的,抱歉,我還沒有被允許投票。 – Jake

1

它認爲這是你處理限制的方式,儘管這應該會觸發一個錯誤。

嘗試:

$beginLimit = ($page_num-1)*$page_rows; 
$endLimit = $page_rows; 
$query = $this->dbh->prepare("SELECT * FROM employee_info ORDER BY employee_id DESC LIMIT :begin,:end"); 
$query->bindValue(':begin',(int)$beginLimit,PDO::PARAM_INT); 
$query->bindValue(':end',(int)$endLimit,PDO::PARAM_INT); 
$query->execute(); 
+0

非常感謝凱西,不幸的是我沒有被允許投票,但這是非常感謝。 – Jake