【问题标题】:pdo WHERE IN checkboxes + multiselectpdo WHERE IN 复选框 + 多选
【发布时间】:2015-04-10 10:38:44
【问题描述】:

2 月编辑。 2015年11月11日-11:38

我花了几个小时寻找正确的解决方案,但没有实现我的目标。我只想在我的 WHERE IN 请求中读取我的 multiselect[] 和 checkboxes[] 的选定值。 我已经尝试了几个小时不同的解决方案,但我仍然完全陷入困境。

感谢您的帮助

$secteur_searched="";
if (!empty($_REQUEST['secteur_searched']) AND is_array($_REQUEST['secteur_searched']))
   { foreach ($_REQUEST["secteur_searched"] as $selectedOption)        
     $secteur_searched.=$selectedOption.",";  
   }

if ($secteur_searched)
   { $secteur_searched = rtrim($secteur_searched, ',');
     $where[] = "j.job_secteur IN (:job_secteur) " ;
     $param[':job_secteur']= $secteur_searched;  
     var_dump($secteur_searched); // returns (1,2,3)
   }

if (!empty($where)) 
   { $query.= ' WHERE ' . implode(' AND ', $where);
   }

 $query.= " ORDER BY j.job_date_insertion DESC"; 
 $sth =$marInterim ->prepare($query);
 $sth->execute($param);

 $compte = $sth->fetchAll();
 $nb_resultats = count($compte); 
 $errors['nb_resultats_recherche'] = $nb_resultats; // ok (for ajax)

/********************/
 if ( !empty($_REQUEST['afficher_x_resultats']))
    { $per_page=$_REQUEST['afficher_x_resultats']; 
    }
 else {$per_page=10; }

/* Results per page */
$nb_pages = ceil($nb_resultats/$per_page);  
$current_page = isset($_REQUEST['page']) && ($_REQUEST['page'] > 0) && ($_REQUEST['page'] <= $nb_pages) ? $_REQUEST['page'] : 1;
$start = ($current_page-1)*$per_page;    

$query2= $query." LIMIT $start,$per_page "; 
$sth2 =$marInterim ->prepare($query2); 
$sth2-> execute($param); 
//print_r($sth2->errorInfo());

 while($datos= $sth2->fetch(PDO::FETCH_ASSOC))
  { $en_date_insertion=$datos['job_date_insertion'];      
 $explode_insertion= explode("-", $en_date_insertion);
 $date_insertion_fr = $explode_insertion[2]."-".$explode_insertion[1]."-".$explode_insertion[0];         
 $job_id= $datos['job_id'];
 $job_intitule= strtoupper($datos['job_intitule']);
 $job_ville = $datos['ville_nom'];
 $job_cp = $datos['cp'];
    echo 'hello';        
echo "
                                   <div class='offers btns'>
                                   <a class='link_vers_offre' href='job_offer_detail.php?job_id=$job_id'>
                                   <table id='table_liste_des_offres'>
                                   <tr>
                                   <td class='liste_intitule'> " .$job_intitule." </td>
                                   <td class='liste_ref'>Offre n°" .$job_id."   du   ".$date_insertion_fr ." </td>
                                   <td class='liste_ville'> ".$job_cp. " ".$job_ville." </td>
                                   </tr>
                                   </table>
                                   </a>
                                   </div>
                                 ";
  }

【问题讨论】:

  • 函数参数(一旦更正)返回:SELECT * FROM marinterim_job_offers j JOIN marimmo_villes v ON v.ville_id =j.job_ville WHERE j.job_secteur IN ('1,2,3,4,5,6,13') ORDER BY j.job_date_insertion DESC LIMIT 0,10
  • 我发现了,并且明白数组中包含的所有值都必须被引用,但我不知道如何将下面的代码与我的匹配。 $idlist = array('260','201','221','216','217','169','210','212','213'); $questionmarks = str_repeat("?,", count($idlist)-1) . "?"; $stmt = $dbh-&gt;prepare("DELETE FROM foo` WHERE id IN ($questionmarks)");`

标签: php pdo where-in


【解决方案1】:

你猜对了,我的选择和复选框名称包含 [] :

 <select multiple="multiple" name="secteur_searched[]" size="8">
  <option value="12">Informatique - Technologie de l'Information</option>
  <option value="14">Logistique - Manutention - Transport</option>
// and so on ...
</select>

 <input type="checkbox" name="type_de_contrat[]" value="CDI" >
 <input type="checkbox" name="type_de_contrat[]" value="CDD" >

等等……

当我尝试您的方法时(谢谢!),这似乎是正确的,我没有从数据库中得到任何回报。 (我为测试填写的唯一输入是多选)。

   $secteur_searched="";

   if (!empty($_REQUEST['secteur_searched']) AND is_array($_REQUEST['secteur_searched']))
      { foreach ($_REQUEST["secteur_searched"] as $selectedOption)        
        $secteur_searched.=$selectedOption.",";  
      }

  if ($secteur_searched)
     { $secteur_searched = rtrim($secteur_searched, ',');
       $where[] = "j.job_secteur IN (:job_secteur) " ;
       $param[':job_secteur']= $secteur_searched;  
       var_dump($secteur_searched); // returns (1,2,3)
     }

 if (!empty($where)) 
    { $query.= ' WHERE ' . implode(' AND ', $where);
    }

 $query.= " ORDER BY j.job_date_insertion DESC"; 

 $sth =$marInterim ->prepare($query);
 $sth->execute($param);

 while($datos= $sth->fetch(PDO::FETCH_ASSOC))
  { $en_date_insertion=$datos['job_date_insertion'];      
     $explode_insertion= explode("-", $en_date_insertion);
     $date_insertion_fr = $explode_insertion[2]."-".$explode_insertion[1]."-".$explode_insertion[0];         
     $job_id= $datos['job_id'];
     $job_intitule= strtoupper($datos['job_intitule']);
     $job_ville = $datos['ville_nom'];
     $job_cp = $datos['cp'];
echo "
                                       <div class='offers btns'>
                                       <a class='link_vers_offre' href='job_offer_detail.php?job_id=$job_id'>
                                       <table id='table_liste_des_offres'>
                                       <tr>
                                       <td class='liste_intitule'> " .$job_intitule." </td>
                                       <td class='liste_ref'>Offre n°" .$job_id."   du   ".$date_insertion_fr ." </td>
                                       <td class='liste_ville'> ".$job_cp. " ".$job_ville." </td>
                                       </tr>
                                       </table>
                                       </a>
                                       </div>
                                     ";

  }

【讨论】:

    【解决方案2】:

    您没有提供您正在使用的 html。因此,假设您必须遵循由多选、复选框列表和按钮组成的表单。

    <form id="frm" name="frm" method="POST">
        <select name="secteur_searched[]" id="secteur_searched" multiple="multiple">
            <option value="secteur_searched_1" selected>secteur_searched_1</option>
            <option value="secteur_searched_2">secteur_searched_2</option>
            <option value="secteur_searched_3" selected>secteur_searched_3</option>
            <option value="secteur_searched_4">secteur_searched_4</option>
        </select>
        <br/>
        <input type="checkbox" name="type_de_contrat[]" value="type_de_contrat_1" checked="checked" />type_de_contrat_1
        <input type="checkbox" name="type_de_contrat[]" value="type_de_contrat_2" checked="checked" />type_de_contrat_2
        <input type="checkbox" name="type_de_contrat[]" value="type_de_contrat_3" />type_de_contrat_3
        <input type="submit" value="POST VALUES" id="cmd" name="cmd"/>
    </form>
    

    如果您希望访问所有复选框/多选值posted,您需要在对象的name 属性中指定的值末尾添加[]。比如

    <select name="secteur_searched[]"></select>
    

    <input type="checkbox" name="type_de_contrat[]" />
    

    这是您在服务器端访问发布值的方式。

    多选

    foreach ($_POST["secteur_searched"] as $selectedOption)
      echo $selectedOption."<br/>";
    

    复选框

    foreach ($_POST["type_de_contrat"] as $selectedCheckbox)
      echo $selectedCheckbox."<br/>";
    

    表单发布时打印出值的完整代码

    if (isset($_POST["cmd"]))
    {
      if (isset($_POST["secteur_searched"]))
      {
        foreach ($_POST["secteur_searched"] as $selectedOption)
          echo $selectedOption."<br/>";
      }
    
      if (isset($_POST["type_de_contrat"]))
      {
        foreach ($_POST["type_de_contrat"] as $selectedCheckbox)
          echo $selectedCheckbox."<br/>";
      }
    }
    

    下一步是构造pdo对象要使用的参数。这是一个示例代码。

    if (isset($_POST["cmd"]))
    {
        $secteur_searched=""; //$param[':job_secteur']
        $type_de_contrat_searched=""; //$param[':type_de_contrat']
        if (isset($_POST["secteur_searched"]))
        {
          foreach ($_POST["secteur_searched"] as $selectedOption)
            $secteur_searched.=$selectedOption.",";
        }
    
        if (isset($_POST["type_de_contrat"]))
        {
            foreach ($_POST["type_de_contrat"] as $selectedCheckbox)
                $type_de_contrat_searched.=$selectedCheckbox.",";
        }
    
        if ($secteur_searched)
          $secteur_searched = rtrim($secteur_searched, ','); //get rid of the "," at the end 
    
        if ($type_de_contrat_searched)
          $type_de_contrat_searched= rtrim($type_de_contrat_searched, ','); //get rid of the "," at the end
    
       echo "type_de_contrat_searched:".$type_de_contrat_searched."<br/>secteur_searched:".$secteur_searched;
    }
    

    编辑 1

    我想您遇到的问题是访问发布的值。如果不是这样,请告诉我。

    编辑 2

    我不确定你是否尝试过,所以无论如何我都会放下它。检查您的参数绑定是否正确

    $sth2->debugDumpParams();
    

    在你表演之后

    $sth2->execute($param); 
    

    编辑 3

    显然debugDumpParams 没有打印出参数的值。

    尽管有文档,但此函数不会打印参数值 说是的。见https://bugs.php.net/bug.php?id=52384(归档回 2010)。

    manual页面找到一个有用的功能如下

    function parms($string,$data) {
        $indexed=$data==array_values($data);
        foreach($data as $k=>$v) {
            if(is_string($v)) $v="'$v'";
            if($indexed) $string=preg_replace('/\?/',$v,$string,1);
            else $string=str_replace(":$k",$v,$string);
        }
        return $string;
    }
    

    (也许你已经知道那个了)用它来显示这样准备好的sql

    print parms($query2,$param); //query,your parameter array
    

    【讨论】:

    • 非常感谢您提供的所有帮助,Ozgur 酒吧。糟糕,我不知道输入 Enter 会发布消息。让我完成它。我会在几分钟后回来。谢谢。
    • 你在echo $query;$sth =$marInterim -&gt;prepare($query);之前看到了什么?
    • 如果我为 secteur_searched 选择所有可能的值:$query = SELECT * FROM marinterim_job_offers j JOIN marimmo_villes v ON v.ville_id =j.job_ville WHERE j.job_secteur IN (1,2,3, 4,5,6,13,8,9,10,11,12,14,15,16,7,17​​,18) ORDER BY j.job_date_insertion DESC
    • 对我来说看起来不错。 print_r($sth-&gt;errorInfo()); 中的任何内容?
    • Array ([0] => 00000 [1] => [2] =>) - 很棒的信息!我应该明白什么?再次感谢
    【解决方案3】:

    这个函数只返回

    SELECT * FROM marinterim_job_offers j JOIN marimmo_villes v ON v.ville_id =j.job_ville WHERE j.job_secteur IN (:job_secteur) ORDER BY j.job_date_insertion DESC LIMIT 0,10

    function parms($query2,$param) {
    $indexed=$param==array_values($param);
    foreach($param as $k=>$v) {
        if(is_string($v)) $v="'$v'";
        if($indexed) $query2=preg_replace('/\?/',$v,$query2,1);
        else $query2=str_replace(":$k",$v,$query2);
    }
    return $query2;
    } print parms($query2,$param); 
    

    然后,$sth2->debugDumpParams();

    [186] SELECT - FROM marinterim_job_offers j JOIN marimmo_villes v ON v.ville_id =j.job_ville WHERE j.job_secteur IN (-job_secteur) ORDER BY j.job_date_insertion DESC LIMIT 0,10 Params- 1 Key- Name- [12 ] -job_secteur paramno=-1 name=[12] --job_secteur-is_param=1 param_type=2


    我注意到,如果我当时在 MultiSelect 中仅选择 1 个选项,我会得到相应的结果... 例如:option value='5' -> 返回对应于 job_secteur 5 的结果..

    <select multiple="multiple" name="secteur_searched[]" .../>
    

    谢谢

    【讨论】:

    • 我认为您需要将$query2=str_replace(":$k",$v,$query2); 更改为$query2=str_replace("$k",$v,$query2);,因为您的键中已经有“:”。 ps:为什么你一直发布答案而不是更新问题?你让人们更难追踪。
    • 好吧好吧,也许我可以更新我的帖子 n°1 并删除所有其他的。感谢您指出/您的建议。
    猜你喜欢
    • 2014-07-07
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多