我一直在
'SQLSTATE [42000]:语法错误或访问冲突:1064您有 SQL语法错误;查看与您的手册相对应的手册 MySQL服务器版本,用于在第5行''/'附近使用'5'附近的正确语法
'5'是从下拉框中选择的任何数字。
这是我到目前为止关于这个问题的代码。
if (isset($_GET['orderBy']) && $_GET['orderBy'] == 'rank' || $_GET['orderBy'] == 'release_year' || $_GET['orderBy'] == 'author'
|| $_GET['orderBy']== 'publisher')
if (isset($_GET['returnLimit']) && $_GET['returnLimit'] == 1 || $_GET['returnLimit'] == 5 || $_GET['returnLimit'] == 10
|| $_GET['returnLimit'] == 25 || $_GET['returnLimit'] == 50 || $_GET['returnLimit'] == 75
|| $_GET['returnLimit'] == 100)
{
try{
$db = new PDO ("mysql:host=localhost;dbname=user", "user", "12345");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$minimum = $_GET['minimumYear'];
$maximum = $_GET['maximumYear'];
$order = $_GET['orderBy'];
$limit = $_GET['returnLimit'];
$q = "SELECT *
FROM book
WHERE '$minimum' <= '$maximum'
ORDER BY '$order'
LIMIT '$limit'";
$query = $db->query($q);
$statement = $db->prepare($query);
$statement->execute();
从我得到的错误中,我猜它正在显示,因为没有数字被传递到$ limit,所以SQL查询没有'LIMIT'。我检查了语法,但无法弄清楚我做错了什么,任何帮助都会受到赞赏。
答案 0 :(得分:1)
您的代码至少存在四个主要问题,可能更多。
将您的代码更改为
if (
isset($_GET['orderBy'])
&& in_array($_GET['orderBy'], array('rank','release_year','author','publisher'))
&& isset($_GET['returnLimit']
&& in_array($_GET['returnLimit'], array(1,5,10,25,50,75,100))
)
{
$db = new PDO ("mysql:host=localhost;dbname=user", "user", "12345");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$min = $_GET['minimumYear'];
$max = $_GET['maximumYear'];
$order = $_GET['orderBy'];
$limit = $_GET['returnLimit'];
$q = "SELECT * FROM book WHERE release_year BETWEEN ? AND ?
ORDER BY $order LIMIT $limit";
$statement = $db->prepare($q);
$statement->execute(array($min, $max));
$data = $statement->fetchAll();