我正在嘗試創建一個可以抓取表內所有帖子的函數。我也想添加一個可選的LIMIT參數。這裏是一個例子:可選LIMIT用於抓取所有PDO的帖子
function get_all_posts($conn, $limit = 0) {
if ($limit > 0) {
$stmt = $conn->prepare("SELECT * FROM posts LIMIT :limit");
$stmt->execute(array(
':limit' => $limit
));
$results = $stmt->fetchAll();
return $results ? $results : false ;
} else {
$stmt = $conn->prepare("SELECT * FROM posts");
$stmt->execute();
$results = $stmt->fetchAll();
return $results ? $results : false ;
}
}
如果我不使用限制參數調用該函數它的作品,並顯示所有帖子。但是,如果我像這樣調用函數:get_all_posts($ conn,「1」);然後我得到這個錯誤:
Fatal error: Uncaught exception 'PDOException' with message '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 ''1'' at line 1' in /Applications/MAMP/htdocs/sandbox/blog2/functions.php:19 Stack trace: #0 /Applications/MAMP/htdocs/sandbox/blog2/functions.php(19): PDOStatement->execute(Array) #1 /Applications/MAMP/htdocs/sandbox/blog2/index.php(12): get_all_posts(Object(PDO), '1') #2 {main} thrown in /Applications/MAMP/htdocs/sandbox/blog2/functions.php on line 19
任何人都可以告訴我我哪裏出了錯?
你是一個拯救生命的人,謝謝! 你說MySQL可能會處理這個問題,但在我的情況下,這並不意味着它在某些情況下會起作用,有些情況下不會呢? – Ben
根據我們的配置,MySQL有時在字符串到整數的比較上是寬鬆的。無論如何,我認爲最好在這種情況下將'limit'作爲一個整數來綁定。看起來像** hakre **已經提供了一個代碼示例。 –