Php SQL查询未正确完成-不确定原因
好,, 我在一个名为week select的页面上有一个多选下拉列表,它的选择通过ajax传递到我的php页面 我可以很好地获取数据,但是当查询运行时,它不会正确地完成 我有这个:Php SQL查询未正确完成-不确定原因,php,html,mysql,sql,Php,Html,Mysql,Sql,好,, 我在一个名为week select的页面上有一个多选下拉列表,它的选择通过ajax传递到我的php页面 我可以很好地获取数据,但是当查询运行时,它不会正确地完成 我有这个: //Deal with Week Array $weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 wee
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
如果我只选择一周,它工作得很好,并显示适当的数据
如果我选择多个选项(例如第12周、第14周和第15周),它将运行查询,但只显示第12周
当我在SQL中手动输入查询时,我想象这个查询是如何被输入的——它运行并显示适当的数据。所以,如果我把SELECT*从mytablename中放到WK所在的位置(12、14、15),它就得到了我想要的东西
我不明白为什么我的查询在这里没有正确执行。
有什么想法吗
**编辑:在将数组传递到后端之前,我在前端使用javascript将多个选择中的数组设置为字符串。我认为不能将数组绑定到单个的
?
占位符。通常,您必须输入尽可能多的?
值,就像数组中的元素一样。您对值的查询结果可能如下所示,在中只有一个值:
… WK IN ("12,14,15") …
为每个原子值使用一个占位符:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
或使用,而不是在:
$sql[] = " FIND_IN_SET(WK, ?) ";
如果您的HTML是正确的,并且您的周选择具有name=“week[]”
,那么您将使用$\u get['week']返回一个数组代码>,否则如果没有[]
,它将只给您1个值。然后,您正在执行字符串替换,但它不是字符串。相反,请尝试以下方法:
$weekFilter = implode(',', $_GET['week']);
为什么不在执行multipe select时简单地回显查询,然后在一秒钟内看到问题…我认为您在这里的路径是正确的-in可能正在查看单个值。试着让你的示例代码工作(它不适合我,我还在学习)。目前,它在$sql[]=行上给出了以下错误:“语法错误,意外的“;”in”。不过,这让我朝着一个好的方向前进。@Hanny只缺少了一个)
。仍然得到了一个错误:“array_fill()需要3个参数,其中2个参数在…”但是到达那里:)仍然在挖掘-我想你让我走上了正确的道路。看看我是否能让它工作。另外,为了它的价值,我在将数组传递到后端的PHP之前,在前端使用javascript将数组设置为字符串。@Hanny好的,也解决了这个问题。