title: PHP loops and binding queries in MySQL
body: <p><strong>Context</strong></p>
  
  <p>I'm trying to write an efficient and secure search script using PHP and MySQL which will prevent SQL injection attempts. I'm using the MySQLi suite of functions and specifically binding user input to the database queries. Because users may be searching for multiple words at a time I have developed a method to dynamically bind variables to a MySQLi query but am getting stuck in one particular place.</p>
  
  <p>I have an example table of users and a table of all the skills the users have:</p>
  
  <pre><code>USERS:               SKILLS:
  ID | Username        Userid  | Skill
  1  | Patty           1       | Decorating
  2  | Billy           1       | Renovating
                       2       | Painting
                       2       | Flooring
  </code></pre>
  
  <p>I have produced a search query which explodes all of the search terms a visitor has searched for and then runs them through a MYSQLi query:</p>
  
  <pre><code>$searched = explode (' ', stripslashes ($search)); // What the visitor searched for
  
  $bindParam = new BindParam (); // Initiate the dynamic binding class
  $qArray = array (); 
  
  foreach ($searched as $sd) {    
      $sd = trim ($sd);   
      if ($sd != '') {
          $qArray[] = 'skills.skill LIKE CONCAT(?,\'%\')'; // Use arrays to construct part of the dynamic query
          $bindParam-&gt;add ('s', $sd); // Users are searching for strings so use 's' as opposed to 'i' for integer for example
      }
  }
  
  $query = "SELECT username FROM users WHERE users.id IN (SELECT skills.userid FROM skills WHERE ";
  $query .= implode (' OR ', $qArray);
  $query .= ")"; // Join the query together
  
  $stmt = $mysqli-&gt;prepare ($query) or die ("Prepare failed: (" . $mysqli-&gt;errno . ") " . $mysqli-&gt;error);    
  call_user_func_array (array ($stmt, "bind_param"), $bindParam-&gt;get ()); // Bind the variables to the query
  
  $stmt-&gt;execute ();
  $stmt-&gt;store_result ();
  
  if ($stmt-&gt;num_rows &gt; 0) {              
      $stmt-&gt;bind_result ($username);
      $searchoutput = array ();
      while ($stmt-&gt;fetch ()) {
          $searchoutput[] = $username; // send all usernames to an array      
      }
  
  print_r ($searchoutput); // print all contents of the array
  
  }
  </code></pre>
  
  <p><strong>The Question</strong></p>
  
  <p>Now, when the visitor searches for <strong>"decorating renovating painting"</strong> the code returns:</p>
  
  <pre><code>Array ( [0] =&gt; patsy [1] =&gt; billy )
  </code></pre>
  
  <p>...as the MySQL query is effectively ignoring the fact that Patsy comes up twice. Ideally I would like the array to actually show:</p>
  
  <pre><code>Array ( [0] =&gt; patsy [1] =&gt; patsy [2] =&gt; billy )
  </code></pre>
  
  <p>Unless I incorporate the query into a loop based on the number of search terms, How can I solve this?</p>