dooo61733 2013-03-03 00:34
浏览 28
已采纳

PHP - 通过QueryString循环

Trying to loop through a querystring in php but only getting last value. What should I be doing to get all values?

example: querystring = ?style=ranch&style=barn&style=colonial

php:

$sqlStyle = "SELECT DISTINCT COUNT(*) as count  FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
    if ($i == 1){
        $sqlStyle .= "where ";
     }else{
        $sqlStyle .= " and ";
    }
    $sqlStyle .=  $key . " like '%" . $value ."%'";
    $i++;
 }
 echo $sqlStyle;

Result: SELECT DISTINCT COUNT(*) as count FROM houses_single Where Houses like '%colonial%'

  • 写回答

1条回答 默认 最新

  • dongzanghong4379 2013-03-03 00:41
    关注

    The query parameter "style" is an array in this case and must be identified by square brackets - if not, the last key=value pair will overwrite the others.

    ?style[]=ranch&style[]=barn&style[]=colonial
    

    $_GET['style'] is an array then you can loop over by using foreach:

    foreach ($_GET['style'] as $value) {
        // ...
    }
    

    if 'style' is not the only parameter you want to add, you can use a is_array() check in the foreach loop:

        foreach ($_GET as $key => $value) {
            if ($i == 1){
                $sqlStyle .= "where ";
             }else{
                $sqlStyle .= " and ";
             }
    
             if(is_array($value)) {
                 $sec = array();
                 foreach($value as $second_level) {
                     $sec[] =  $key . " LIKE '%" . $second_level."%'";
                 }
                 $sqlStyle .= implode(' AND ', $sec);
             }
             else {
                $sqlStyle .=  $key . " LIKE '%" . $value ."%'";
             }
    
             $i++;
         }
         echo $sqlStyle;
    

    alternative without foreach:

    <?php
    
    $statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
    
    if(is_array($_GET)) {
       $statement .= ' WHERE';
    
       // create copy to keep the $_GET array
       $add_where = $_GET;
    
       array_walk(function($elem,$key){
          is_array($elem) {
             return implode(' AND ', array_map(function($sec) using ($key)  {
                 return "$key LIKE '%$sec%'";
             }, $elem);
          }
          else {
                return "$key LIKE '%$elem%'";
          }
       },$add_where);
    
       $statement .= implode(' AND ', $add_where);
    }
    

    (codes are untested)

    Sidenode about safety: I hope you won't use this code snippet you provided in productive environment without any escaping of the parameters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法