我正在尝试使用Doctrine编写一个准备好的SQL语句。 如果我在SQL查询中硬编码它正在运行:
public function search()
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = "myfile.exe"';
$query = $this->conn->prepare($sql);
$status = $query->execute();
$searchResult = $query->fetchAll();
$searchResult = array(
'service' => $searchResult,
'status' => $status
);
$searchResult = $this->conn->fetchAll($sql);
return $searchResult;
}
但是,如果我尝试使用参数传递值,则不会给出 PDOException:SQLSTATE [42000]
public function search()
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = :service';
$query = $this->conn->prepare($sql);
$query->bindValue(":service", "myfile.exe");
$status = $query->execute();
$searchResult = $query->fetchAll();
$searchResult = array(
'service' => $searchResult,
'status' => $status
);
$searchResult = $this->conn->fetchAll($sql);
return $searchResult;
}
我无法弄清楚我做错了什么。
答案 0 :(得分:0)
应该是:
public function search(){
$sql = 'SELECT `name` FROM `files` WHERE `name` = ?';
$query = $this->conn->prepare($sql);
$query->bindValue(1, "myfile.exe");
$status = $query->execute();
$searchResult = $query->fetchAll();
$searchResult = array(
'service' => $searchResult,
'status' => $status
);
$searchResult = $this->conn->fetchAll($sql);
return $searchResult;
}
答案 1 :(得分:0)
啊 - 我现在看到它,它是文件名周围的引号。 试试这个(可能会有效):
$query->bindValue(':service', '"myfile.exe"');
答案 2 :(得分:0)
在坚持这个问题2天后,我终于找到了解决方案。 我只是删除了这一行:
$searchResult = $this->conn->fetchAll($sql);
所以下面的代码工作正常:
public function search($service)
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = ":service"';
$query = $this->conn->prepare($sql);
$query->bindValue(":service", $service);
$status = $query->execute();
$searchResult = $query->fetchAll();
$searchResult = array(
'service' => $searchResult,
'status' => $status
);
return $searchResult;
}
谢谢大家的帮助。
答案 3 :(得分:-2)
在传递文件名时你是否会丢失一组引号?我做的PHP不多。我发表评论,但我的代表太低了。
这有用吗?
public function search()
{
$sql = 'SELECT `name` FROM `files` WHERE `name` = ":service"';
$query = $this->conn->prepare($sql);
$query->bindValue(":service", "myfile.exe");
$status = $query->execute();
$searchResult = $query->fetchAll();
$searchResult = array(
'service' => $searchResult,
'status' => $status
);
$searchResult = $this->conn->fetchAll($sql);
return $searchResult;
}