gpt4 book ai didi

mysql - PDO 使用 bindParam 返回 MySQL 错误

转载 作者:行者123 更新时间:2023-11-29 06:05:55 26 4
gpt4 key购买 nike

嘿伙计们,我在这里运行这个小功能

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 beach 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 文档:

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

编辑正如@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();

关于mysql - PDO 使用 bindParam 返回 MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com