我有一个具有多个复选框的基本表单.选中复选框后,它将把值附加到ajax调用的URL中.将这些值传递给mypage.php?item1 = 1& item2 = 2& item3 = 3之后,我正在使用GET [‘item’]检索和存储这些值,以便在SQL查询中使用.此问题的复杂性在于,由于它基于复选框,因此传递的值量可能会有所不同.例如,您可以传递1个值或传递所有三个值.我的问题是:如何使这种动态变化适用于sql查询?如果传递了多个值,则查询将在WHERE子句中要求对其他项进行AND.
$('#submitForm').click(function() {
var url = "'www.mysite.com/mypage.php";
if ($("#checkbox_form").serialize().length > 0) {
url += "?" + $("#checkbox_form").serialize();
}
$.getJSON(url)
});
mypage.php?item1 = 1& item2 = 2
$item = $_GET['item#'];
$sql_query = "SELECT info From Products Where :item# AND item#";
$sql_prepare = $db_con->prepare($sql_query);
if (!$sql_prepare->execute(array(':item#' => $item)))
//rest of code
解决方法:
首先,您需要创建一个输入数组,而不是“ val1”,“ val2”.
只需给每个输入一个val [x]的名称,例如val [1],val [2]等.或者,您可以让它成为一个新的数组元素:val [].
然后,您需要在构建查询之前使用PHP foreach处理此问题,例如:
$sql_query = "SELECT info From Products";
$conditions = array();
if (isset($_GET['val']) && is_array($_GET['val'])) {
$vals = $_GET['val'];
foreach ($vals as $key => $val) {
$conditions[] = '`field'. $key .'` = '. $val;
// You should change the conditions the way you want, I'm not sure about what you want here.
}
}
if (count($conditions) > 0) {
$sql_query .= ' where '. implode(' and ', $conditions);
}
您完成了!
更新
如评论中所述,这是您要寻找的条件:
foreach ($vals as $val) {
$conditions[] = '`item_id` = '. $val;
}
此外,在这种情况下,请不要忘记您是否需要AND.因此,也请编辑此行:
$sql_query .= ' where '. implode(' or ', $conditions);
标签:mysql,php
来源: https://codeday.me/bug/20191122/2057723.html