我想使用一个准备好的语句,其中传入的参数用于 ORDER BY
和 LIMIT
子句,如下所示:
I want to use a prepared statement in which the passed-in parameters are for the ORDER BY
and LIMIT
clauses, like so:
$sql = 'SELECT * FROM table ORDER BY :sort :dir LIMIT :start, :results';
$stmt = $dbh->prepare($sql);
$stmt->execute(array(
'sort' => $_GET['sort'],
'dir' => $_GET['dir'],
'start' => $_GET['start'],
'results' => $_GET['results'],
)
);
但是 $stmt->fetchAll(PDO::FETCH_ASSOC);
什么都不返回.
But $stmt->fetchAll(PDO::FETCH_ASSOC);
returns nothing.
有人能指出我做错了什么吗?可以做到吗?如果没有,我应该参考哪些可以使用参数的子句的完整列表?
Can someone point out what's the wrong thing I am doing? Can it be done? If not,what should I reference for a complete list of clauses where parameters can be used?
使用后:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
我收到了消息:
未捕获的异常 'PDOException' 与消息SQLSTATE[42000]:语法错误或访问冲突:1064 你有一个SQL 语法错误;检查与您的 MySQL 相对应的手册正确语法的服务器版本在第 1 行的0"、10"附近使用
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''0', '10'' at line 1
因此,当您使用数组进行执行时,它会将您的输入视为字符串,这对于 LIMIT 来说不是一个好主意
So, when you use an array for execute, it consider your inputs as string which is not a good idea for LIMIT
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM table ORDER BY :sort :dir LIMIT :start, :results";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':start', $_GET['start'], PDO::PARAM_INT);
$stmt->bindParam(':results', $_GET['results'], PDO::PARAM_INT);
$stmt->bindParam(':sort', $_GET['sort']);
$stmt->bindParam(':dir', $_GET['dir']);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($data);
这篇关于如何将 pdo 的准备好的语句用于 order by 和 limit 子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!