PHP的SQL准备选择查询不返回任何东西(PHP SQL prepared select query not returning anything)

编程入门 行业动态 更新时间:2024-10-24 02:02:33
PHP的SQL准备选择查询不返回任何东西(PHP SQL prepared select query not returning anything)

当我运行下面的代码时,它什么都不返回。 当我在'?'的位置显式地输入一个字符串时,它会返回预期的结果,但是使用准备好的版本到目前为止还没有为我工作。 我不认为存在任何种类的版本控制问题,因为过去使用INSERT查询的准备语句对我有用。 准备好的声明可能是什么问题?

$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass); $sql = "SELECT * FROM table WHERE column LIKE '%?%';"; $stmt = $pdo->prepare($sql); $stmt->execute(array($_GET['searchterm'])); $results = $stmt->fetchAll(); print_r($results);

When I run the code below, it returns nothing. When I explicitly type a string in the place of the '?', it will return the expected result but using the prepared version has not worked for me thus far. I do not believe there is any kind of versioning issue as using prepared statements for INSERT queries has worked for me in the past. What might be the problem here with the prepared statement?

$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass); $sql = "SELECT * FROM table WHERE column LIKE '%?%';"; $stmt = $pdo->prepare($sql); $stmt->execute(array($_GET['searchterm'])); $results = $stmt->fetchAll(); print_r($results);

最满意答案

您正在准备该值,因此它不像您只是将该字符串放入查询中那样行事。

在准备一个字符串时,你不需要添加"或' ,这是为你完成的,你需要将%添加到你正在转义的值中。

$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass); $sql = "SELECT * FROM table WHERE column LIKE ?;"; $stmt = $pdo->prepare($sql); $stmt->execute(array("%{$_GET['searchterm']}%")); $results = $stmt->fetchAll(); print_r($results);

You are preparing the value so it isn't behaving as if you just put the string inside of the query.

When preparing a string you don't need to add " or ', that is done for you. You need to add the %'s into the value that you are escaping.

$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass); $sql = "SELECT * FROM table WHERE column LIKE ?;"; $stmt = $pdo->prepare($sql); $stmt->execute(array("%{$_GET['searchterm']}%")); $results = $stmt->fetchAll(); print_r($results);

更多推荐

本文发布于:2023-08-07 11:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:东西   SQL   PHP   prepared   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!