gpt4 book ai didi

php - PDO 添加单引号绑定(bind)参数

转载 作者:行者123 更新时间:2023-11-30 23:11:35 24 4
gpt4 key购买 nike

我正在使用 Slim 框架为站点构建 RESTful 后端,使用 PHP 的 PDO 来查询数据库。但是,当我尝试将参数绑定(bind)到准备好的语句时,出现以下错误:

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 用单引号将我的绑定(bind)参数括起来。我的路由代码如下:

$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 在绑定(bind)之前转换为整数,但这也没有什么区别。

最佳答案

可能的解决方案:正确地将参数转换为整数。如果在该方法的第一行中,我使用 $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());
}
});

关于php - PDO 添加单引号绑定(bind)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19539277/

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