2013-10-23 89 views
0

我使用Slim框架爲站點構建RESTful後端,使用PHP的PDO查詢數據庫。然而,當我試圖參數綁定到準備好的聲明,我得到以下錯誤:PDO將單引號添加到綁定參數

string(206) "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 ''10'' at line 1"`

看起來好像是PDO我周圍用單引號綁定參數。我的路線代碼如下:

$app->get("/members/next10/:offset", function($offset) use($app) { 
    $app->response()->header('Content-Type', 'application/json'); 

    try { 
     $pdo = connectToDatabase(); 

     $query = $pdo->prepare("SELECT * FROM `members` LIMIT 10 OFFSET :offset"); 
     $query->bindParam(":offset", $offset, PDO::PARAM_INT); 
     $query->execute(); 

     $result = $query->fetchAll(PDO::FETCH_ASSOC); 

     if (!empty($result)) { 
      echo json_encode($result); 
     } else { 
      $app->response()->status(404); 
     } 
    } catch (PDOException $d) { 
     $app->response()->status(500); 
     var_dump($d->getMessage()); 
    } 
}); 

我錯過了什麼嗎?我嘗試從URL中抓取:offset,並將其分配給$offset,在綁定之前將其轉換爲整數,但這也沒有什麼區別。

+0

可能重複http://stackoverflow.com/questions/5508993/pdo-limit-and-offset – fortune

回答

0

可能的解決方案:正確地將參數強制轉換爲整數。如果在方法的第一行中,我使用$offset = (int) $offset;它的工作原理。以前我試圖在$query->bindParam()方法中進行演員陣容。

路線是這樣的:

$app->get("/members/next10/:offset", function($offset) use($app) { 
    $offset = (int) $offset; 

    $app->response()->header('Content-Type', 'application/json'); 

    try { 
     $pdo = connectToDatabase(); 

     $query = $pdo->prepare("SELECT * FROM `members` LIMIT 10 OFFSET :offset"); 
     $query->bindParam(":offset", $offset, PDO::PARAM_INT); 
     $query->execute(); 

     $result = $query->fetchAll(PDO::FETCH_ASSOC); 

     if (!empty($result)) { 
      echo json_encode($result); 
     } else { 
      $app->response()->status(404); 
     } 
    } catch (PDOException $d) { 
     $app->response()->status(500); 
     var_dump($d->getMessage()); 
    } 
});