title: How can I pass a variable to a WHERE clause using mysqli?
body: <p>I currently have a small search form with only two elements: a text input named <code>search</code> and a "select" box named <code>param</code>. The option selected within that box should be used as a parameter to choose which table column in my DB would be fetched.</p>
  
  <p>Using <code>mysql_</code> functions, something like this could be done:</p>
  
  <pre><code>$param  = $_POST['param' ];
  $search = $_POST['search'];
  
  $query = 'SELECT * FROM table WHERE $param LIKE "%$search%"';
  </code></pre>
  
  <p>But I can't get it to work with the <code>mysqli_</code> syntax. I am trying to use prepared statements, but the best I've done so far is this:</p>
  
  <pre><code>$param  = $_POST['param' ];
  $search = $_POST['search'];
  
  if($param == 'first_name')
  {
      if($prep = $link-&gt;prepare('SELECT * FROM table
                                 WHERE first_name
                                 LIKE CONCAT("%", ?, "%")'))
      {
          $prep-&gt;bind_param('s', $search);
          $prep-&gt;execute();
          $prep-&gt;bind_result($first_name, $last_name);
  
          while($prep-&gt;fetch())
              echo $first_name . ' ' . $last_name;
  
          $prep-&gt;close();
       }
       else
           echo 'Error while preparing statement.';
  }
  else if($param == 'last_name')
  {
      ...
  }
  </code></pre>
  
  <p>But just using a bunch of <code>else if</code>s seems a lot repetitive and unproductive, specially if I have lots of columns to handle.</p>
  
  <p>The first thing I tried was parameter binding - <code>... WHERE ? LIKE ...</code> and <code>$prep-&gt;bind_param('ss', $param, $search)</code> -, but it didn't work (and I still don't know why).</p>
  
  <p>Is there a way of doing it in a more intelligent way?</p>