Search code examples
phpsql-like

How to search text using php if ($text like %admin%)


How to search text using php?

Something like:

$form = $_GET['form'];

if($form like %admin%){
  $form = 1;
}

if($form like %user%){
  $form = 2;
}

and then I can use this query like this:

SELECT * FROM people WHERE type = $form ;

Solution

  • When dealing with user input, you can't be lazy with validation.

    Sahil's answer will set $from to 2 if $_GET['form']=='adminuser'. It also uses stristr() which is not recommended (even by the php manual) for this case for performance reasons.

    Unless you have a valid reason for checking for a substring, you should be checking the entire string. Also, you should use just one condition block rather than two separate if blocks -- this will avoid overwriting $form and doing extra unnecessary function calls.

    if(isset($_GET['form']) && $_GET['form']=='admin'){
        $form=1;
    }else{
        $form=2;  // assuming this should be the default form value
    }
    

    ...or $form=isset($_GET['form']) && $_GET['form']=='admin'?1:2;


    If you are going to continue checking for substrings:

    if(isset($_GET['form']) && strpos($_GET['form'],'admin')!==false){
        $form=1;
    }else{
        $form=2;  // assuming this should be the default form value
    }
    

    ...or $form=isset($_GET['form']) && strpos($_GET['form'],'admin')!==false?1:2;

    Depending on your possible values for $_GET['form'] your validation will be improved if you check for the location of admin -- does the string start with admin or end with it or neither?