PDO使用bindParam返回MySQL错误


PDO returning MySQL error with bindParam

嘿,伙计们,我在这里运行这个小函数

function getBeaches() {
$request=Slim::getInstance()->request();
$args=filter_var_array(func_get_args(),FILTER_SANITIZE_STRING); 
$sql="SELECT * FROM beaches WHERE state=:state AND city=:city"; 
    //  var_export($args); die();
    //  array ( 0 => 'wa', 1 => 'seattle', )
try {
    $db         = getConnection();
    $stmt       = $db->prepare($sql);

        $stmt->bindValue('state',   $args[0], PDO::PARAM_STR); //should bind wa 
        $stmt->bindValue('city',    $args[1], PDO::PARAM_STR); //should bind seattle
        $stmt->execute();
    $stmt       = $db->query($sql);
    $beaches    = $stmt->fetchObject();
    $db         = null;
    echo '{"map": ' . stripslashes(json_encode($beaches)) . '}';
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
    /* {"error":{"text":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 ':state AND city=:city' at line 1}}
     */
}

我得到了我在底部评论的错误,试图运行这样的

mysql$ SELECT * FROM beaches WHERE state='wa' AND city='seattle';

这可能会敲响警钟吗?

您需要在参数名称前加分号:(不是100%true,请参阅编辑)

$stmt->bindValue(':state',   $args[0], PDO::PARAM_STR); //should bind wa 
$stmt->bindValue(':city',    $args[1], PDO::PARAM_STR); //should bind seattle

来自PDOStatement::bindValue():上的PHP文档

参数标识符。对于使用命名占位符准备的语句,这将是形式为:name的参数名称。对于使用问号占位符准备的语句,这将是参数的1索引位置。

编辑正如@jeroen所指出的问题(与你的pastebin中的问题相同),你在从$stmt变量中获取数据之前覆盖了它。在你的代码中,问题大约在第17行:

$stmt->execute();  // $stmt now has query results (from the query with parameters bounded)
$stmt       = $db->query($sql); // You redo the query. Now $stmt has no query results and no parameters are bound
$beaches    = $stmt->fetchObject(); // Statement assumes you want to execute query and does so but not parameters are bound

您可以通过将以上行更改为:来解决此问题

$stmt->execute();
$beaches = $stmt->fetchObject();

不确定它是否有帮助,但我总是使用bindParam而不是bindValue。如果你选择这样做,修改你的活页夹如下:

$stmt->bindParam(':state', $args[0], PDO::PARAM_STR);
$stmt->bindParam(':city', $args[1], PDO::PARAM_STR);

除此之外,你所做的一切对我来说都很好。