使用IN子句基于数组的PDO查询

时间:2018-03-29 18:31:03

标签: php mysql pdo

我从表中获取复选框列表,然后将其相对id传递给AJAX调用,以获取列subcategories中同一表中的子类别。

表名:类别 第1行:id 第2行:类别 第3行:子类别(以逗号分隔的列表) 第4行:郎

问题: 如果选择了多个复选框,则查询仅返回一个id,多次返回。

示例: 类别cat - 子类别:foodwaterhealth 类别table - 子类别:woodmetalplastic

如果选中了复选框cattable,则输出将为

foodwaterhealthfoodwaterhealth

应该是:

foodwaterhealthwoodmetalplastic

感谢您的帮助。

AJAX:

$(document).ready(function () {    
    $('.job_category_checkbox').on('change', function() {

          var val =[];
          var lang = $('#form_language').val();

        $("input[class='job_category_checkbox']:checked").each(function(){
            val.push(this.value);
        });

       $.ajax({
           url: 'handlers/response_checkboxes.php',
           type: 'POST',
           data: {val:val, lang:lang},
           dataType: "html",
        success: function (response) {

            $('#response_checkboxes').html(response);

        }
      });
    return false;

    });
});

PHP(在AJAX调用时返回):

$val = $_POST['val']; 
$lang = $_POST['lang'];    

$val_impl = "'" . implode("','", $val) . "'";
$val_bind = implode(', ', $val);

$load_html_select = $dbh->prepare("SELECT * FROM categories WHERE id IN(:id) ");                
$load_html_select->bindValue(':id', $val_bind);  

if($load_html_select->execute()) {
    $load_html_select->setFetchMode(PDO::FETCH_ASSOC);
}


if ($load_html_select->rowCount() == 0 || empty($val) || $val == "0"){
    if($lang == 'ENG'){
    echo '<div value="022q" disabled selected> Please select a specific job </div>';
    }else{
    echo '<div value="0dwadda" disabled selected> Veuillez sélectionner un travail spécifique </div>';  
    }   
}

while($row = $load_html_select->fetch()) { 

$subcategories = $row['subcategories']; 
$exploded = explode(',', $subcategories);


foreach ($val as $v) { 
foreach ($exploded as $ex) { ?>

<div class="_mb5">
    <div class="d-inline-block first_in">
     <input class="_3cok" id="<?php echo htmlentities($ex);?>" value="<?php echo htmlentities($ex);?>" type="checkbox"></div><div class="d-inline-block" role="check-display">
      <label for="<?php echo htmlentities($ex);?>"> <?php echo htmlentities($ex);?> </label>
    </div>
</div>

 <?php
   }
  }
 } 
?>

0 个答案:

没有答案