我正在尝试编写查询并且是一个php启动器
$minPrice = trim($_REQUEST['minPrice']);
$maxPrice = trim($_REQUEST['maxPrice']);
$minCarat = trim($_REQUEST['minCarat']);
$maxCarat = trim($_REQUEST['maxCarat']);
$color = trim($_REQUEST['color']);
$cut = trim($_REQUEST['cut']);
$clarity = trim($_REQUEST['clarity']);
$type = trim($_REQUEST['type']);
类型,清晰度和剪切是由commans分隔的字符串
例如$ type =“1000,1002,1001”;
$statement = $conn->prepare('SELECT * FROM diamondsList WHERE price >= :minPrice AND price <= :maxPrice AND carat >= :minCarat AND carat <= :maxCarat AND cut IN(' . $cut . ') AND clarity IN ('.$clarity.') AND color IN ('. $color.') AND type IN (' . $type.')');
错误是
{"error":"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 ') AND clarity IN () AND color IN () AND type IN ()' at line 1"}
首先,我不确定查询是否在IN('。$ cut。')给出错误。语法有什么问题?
其次,如果语法固定,查询是否正确?
修复后我有searchDiamonds&minPrice=0&maxPrice=10000&minCarat=0&maxCarat=5&color=2000,2001&type=1000,1001&cut=3000,3001&clarity=4000,4001
这样的查询
表的两个条目如下所列
price carat type color cut clarity
2000 2 1000 2000 3000 4000
然而,没有选择任何东西,我总是得到0结果。
查询应该是什么
答案 0 :(得分:1)
你不能在IN
中使用空字符串。您需要检查是否设置了$cut
,如果查询为空则更改您的查询。像这样:
$statement = $conn->prepare('SELECT * FROM diamondsList WHERE price >= :minPrice AND price <= :maxPrice AND carat >= :minCarat AND carat <= :maxCarat ' . (!empty($cut) ? ('AND cut IN(' . $cut . ')') : '') . ' AND clarity IN ('.$clarity.') AND color IN ('. $color.') AND type IN (' . $type.')');
我在sqlfiddle中测试了你的查询,如果在php中正确格式化它应该可以正常工作:
SELECT * FROM diamondsList
WHERE price >= 0
AND price <= 10000
AND carat >= 0
AND carat <= 5
AND cut IN(3000,3001)
AND clarity IN (4000,4001)
AND color IN (2000,2001)
AND type IN (1000,1001)
答案 1 :(得分:0)
这样的东西可能是你想要的,但我没有测试它。
$minPrice = trim($_REQUEST['minPrice']);
$maxPrice = trim($_REQUEST['maxPrice']);
$minCarat = trim($_REQUEST['minCarat']);
$maxCarat = trim($_REQUEST['maxCarat']);
$color = trim($_REQUEST['color']);
$cut = trim($_REQUEST['cut']);
$clarity = trim($_REQUEST['clarity']);
$type = trim($_REQUEST['type']);
$query = "SELECT * FROM diamondsList WHERE price >= $minPrice AND price <= $maxPrice AND carat >= $minCarat AND carat <= $maxCarat");
$field_info = array('cut' => $cut, 'clarity' => $clarity, 'color' => $color, 'type' => $type);
foreach($field_info as $f, $q) {
if (!empty($q)) {
$query .= " AND $f IN ($q)";
}
}
$statement = $conn->prepare($query);