当我运行下面的代码时,它什么都不返回。 当我在'?'的位置显式地输入一个字符串时,它会返回预期的结果,但是使用准备好的版本到目前为止还没有为我工作。 我不认为存在任何种类的版本控制问题,因为过去使用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);更多推荐
发布评论