我正在尝试在我的表中实现搜索,当我尝试在查询中绑定搜索变量时,我得到了这个讨厌的SQL错误。不绑定它会返回正确的结果,但我不需要某种安全性吗?所以,我将这个查询传递给我的一个类:
$query = "SELECT books.id, title, author, category, cover, owns_book.added FROM books JOIN owns_book ON books.id = owns_book.book_id
WHERE owns_book.u_id ='" . $_SESSION['user_session'] . "'";
可以使用$this->query
访问班级中的查询
我在类中存储了更多的东西,比如结果限制等等,在我尝试添加搜索功能之前,一切都按预期工作。
查询的所有进一步工作都在此方法中完成:
public function getData($page = 1, $limit=5, $orderBy='added' , $order='desc', $search="test"){
$this->limit = $limit;
$this->page = $page;
$this->query .= " AND title LIKE :keyword OR author LIKE :keyword
OR category LIKE :keyword OR owns_book.added LIKE :keyword";
$columns = array('author', 'title', 'category', 'added');
$orderType = array('asc', 'desc');
if(in_array($orderBy, $columns) & in_array($order, $orderType)) $this->query .= " ORDER BY $orderBy $order";
if ( $this->limit == 'all' ) {
$query = $this->query;
}else{
$this->row_start = ( ( $this->page - 1 ) * $this->limit );
$query = $this->query.
" LIMIT :rowStart, :limit";
}
$search = "%".$search."%";
echo $query;
$stmt = $this->conn->prepare($query);
$stmt->bindParam(":keyword", $search, PDO::PARAM_STR);
$stmt->bindParam(":rowStart", $this->row_start, PDO::PARAM_INT);
$stmt->bindParam(":limit", $this->limit, PDO::PARAM_INT);
$stmt->execute();
//doing further work with the result
}
绑定rowStart并按预期限制工作,只有关键字绑定抛出和错误,我不明白为什么。我尝试了不同的东西,例如尝试使用LIKE CONCAT('%', :keyword, '%')
仍然会抛出相同的错误。
我尝试将$search = "%".$search."%";
更改为$search = "'%".$search."%'";
,仍然是同样的错误。
echo $query;
返回:
SELECT books.id,title,author,category,cover,owns_book.added FROM books JOIN owns_book ON books.id = owns_book.book_id WHERE owns_book.u_id ='57'AND title LIKE:keyword OR author LIKE:keyword OR category LIKE:keyword OR owns_book.added LIKE:关键字ORDER BY添加了desc LIMIT:rowStart,:limit
如果我没有绑定搜索变量并且只是像
那样$search = "'%".$search."%'";
$this->query .= " AND title LIKE $search OR author LIKE $search
OR category LIKE $search OR owns_book.added LIKE $search";
我得到了我想要的结果。但我担心这不是正确的方法。