0

I have been attempting to update some code to use prepared statements but haven't been able to get it to work. According to documentation and examples I've read it seems that each field in the SELECT statement needs to be bound separately.

I am building my query based on user input and am not sure if my code will be able to use a prepared statement or if I need to rewrite the script. Basically looking for an example to follow in this situation.

The simplified code I have is below:

$db = mysqli_connect("ip_address", "my_login", "my_pw", "my_db");
    if (!$db) {
         die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());


    $query = "SELECT * FROM tbl_name WHERE 1=1";
    if ($_POST[id] != '') {
        $query = $query. " AND id LIKE '%$_POST[id]%'";
    } 
    if ($_POST[date] != '') {
        $query = $query. " AND bdate LIKE '%$_POST[date]%'";
    } 
    if ($_POST[name] != '') {
        $query = $query. " AND name LIKE '%$_POST[name]%'";
    } 
    if ($_POST[address] != '') {
        $query = $query. " AND address LIKE '%$_POST[address]%'";
    }

    $query = $query. " ORDER BY id, bdate DESC";

     $results = mysqli_query($db, $query);  
     echo $query;
}

Thanks in advance

Cal37
  • 98
  • 1
  • 4
  • 13
  • 1
    Use `name LIKE ?` in the query, use `'%' . $input . '%'` as the bind variable. Make sure to escape `%`, `_` and any other metacharacters that have special meaning in `LIKE`. – DCoder Mar 27 '13 at 19:32
  • 2
    I don't see any prepared statement being used at all. Can you show the code where you tried to implement the prepared statements and indicate what specific problems/errors you are having? – Mike Brant Mar 27 '13 at 19:32
  • or [Binding an unknown number of parameters using mysqli](http://stackoverflow.com/q/12486032) or [Use one bind\_param() with variable number of input vars](http://stackoverflow.com/q/793471) or [MySQL Prepared statements with a variable size variable list](http://stackoverflow.com/q/327274) – mario Mar 27 '13 at 20:12

0 Answers0