dongpan9760 2014-07-13 20:54
浏览 56

PHP PDO搜索使用带有LIKE语句的多个输入字段的问题,即使给出了1个参数,也会给出所有结果

I'll try to show my search form and continue on bits of public method code.

Here's my form (basic):

<form action="" method="get">
        Name:<input type="text" name="name">
            Last Name:<input type="text" name="last_name">
            Age:<input type="text" name="age">
            <input type="submit" value="search" name="search">
        </form>

Moving on to my get method:

public function get($table){
        $ssql = 'SELECT * FROM '.$table.' WHERE `name` LIKE :name || `last_name` LIKE :last_name';
        $name = '%'.$_GET['name'].'%';
        $last_name = '%'.$_GET['last_name'].'%';
        $stm = $this->dbh->prepare($ssql);
        $stm->bindParam(':name',$name,PDO::PARAM_STR);
        $stm->bindParam(':last_name',$last_name,PDO::PARAM_STR);

        $stm->execute();

        echo $stm->rowCount();

        while($result = $stm->fetch(PDO::FETCH_OBJ)){
        echo $result->name.' '.$result->last_name.'<br>';

        }
        }

Basically this should give me results based on my $_GET form fields. My problem is that if I enter name "juris" it does not outputs only 3 rows of juris which are in database but all fields from database. But if I enter lastname and then submit it, it gives out only juris records but then ignores lastname search term.

Shouldn't query like "WHERE etc LIKE "term1" OR etc LIKE "term2" give out results based on OR between 2 given variables? It should separate results if one variable $_get['value'] is given and others are empty?

Got it to work as intended but maybe some one could give a bit cleaner answer how to separate "%%" this wild card?

$ssql = 'SELECT * FROM '.$table.' WHERE (`name` LIKE :name) || (`last_name` LIKE :last_name)';
        if(empty($_GET['name'])){
        $name = "";
        }else {
        $name = '%'.$_GET['name'].'%';
        }
        if(empty($_GET['last_name'])){
        $last_name = "";
        }else{
        $last_name = '%'.$_GET['last_name'].'%';
        }

used if statement to separate %% wildcard.

  • 写回答

2条回答 默认 最新

  • douwayuan3063 2014-07-13 20:58
    关注

    You need to use parenthesis to group the two field comparisons like this:

    SELECT * FROM '.$table.' WHERE (`name` LIKE :name && :name_prov = 1) || (`last_name` LIKE :last_name && :last_name_prov = 1)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。