我在PHP类中有以下方法:
function getAll($search, $start, $limit) {
$search = "%$search%";
$sql = 'SELECT * FROM users WHERE valid = 1 AND user_name LIKE :user_name LIMIT :start, :limit';
$sth = $this->db->prepare($sql);
$sth->bindParam(':user_name', $search);
$sth->bindParam(':start', $start, PDO::PARAM_INT);
$sth->bindParam(':limit', $limit, PDO::PARAM_INT);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
按照我的预期工作。当我尝试使用数组execute()
出错时,我的$search
变量未正确准备导致MySQL错误:
function getAll($search, $start, $limit) {
$search = "%$search%";
$params = [
':user_name' => $search,
':start' => $start,
':limit' => $limit
];
$sql = 'SELECT * FROM users WHERE valid = 1 AND user_name LIKE :user_name LIMIT :start, :limit';
$sth = $this->db->prepare($sql);
$sth->execute($params);
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
我做错了什么?导致SQL错误的区别是什么?
编辑:
我的错误:
致命错误:未捕获的异常' PDOException' with message' SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在' 0',' 3'''在第1行'在/home/ubuntu/workspace/curs24/users.php第69行
PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在' 0',' 3'''第69行/home/ubuntu/workspace/curs24/users.php第1行