PHP PDO MySQL query LIKE -> multiple keywords

后端 未结 3 1134
清酒与你
清酒与你 2020-12-04 04:06

I have a users table in MySQL and would like a search by name. Right now I have the following code:



        
相关标签:
3条回答
  • 2020-12-04 04:29

    Please check the below code.

    <?php
    $search = isset($_GET['q']) ? $_GET['q'] : '';
    $search = strtoupper($search);
    $search = strip_tags($search);
    $search = trim($search);
    
    $split_words = explode(" ", $search);
    
    $query = "SELECT * FROM `users`";
    
    if(count($split_words) > 0){
     $query .= " WHERE "
     for($i=0 ; $i < $split_words; $i++){
       $query .= " name LIKE ? OR ";
     }
     $query = substr($query , 0, -3); //Remove last 3 characters OR with space
    
    
     array_walk($split_words,"addPercentage");
    
     $query->execute($split_words);
    }else{
     $query->execute();
    }
    
    $result = $query->rowCount();
    echo $result;
    
    function addPercentage(&$value,$key)
    {
      $value = "%".$value."%" ;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-04 04:45

    You shouldn't use @ to silence errors it is a bad practice, check if the value is set. The example below should work, but the results might not be all that relevant.

    $search = isset($_GET['q']) ? $_GET['q'] : ''; 
    $search = strtoupper($search);
    $search = strip_tags($search); 
    $search = trim($search);
    $words = explode(' ', $search);
    $words_condition = array();
    $arguments = array();
    foreach ($words as $word) {
        $words_condition[] = 'name LIKE ?';
        $arguments[] = '%'.$word.'%';
    }
    
    $query = $con->prepare('SELECT * FROM `users` WHERE '.implode(' OR ', $words_condition));
    $query->execute($arguments);
    
    $result = $query->rowCount();
    echo $result;
    
    0 讨论(0)
  • 2020-12-04 04:49
    $words = explode(" ", $search);
    
    $i = 0;
    while($words[i] != null)
    {
        //Query where name LIKE words[i]
    }
    
    0 讨论(0)
提交回复
热议问题