在mysqli中多次使用相同的绑定器

时间:2018-01-23 07:21:33

标签: php mysql mysqli

我正在写一个小的PHP程序,我是PDO的新手 我的程序中有一个实时搜索组件。
用户的查询应使用两个表格列进行搜索 我知道如何用传统的mysql编写查询。

$sql = 'SELECT * FROM items WHERE (i_name LIKE ='%$query%') OR (i_code LIKE '%$query%')';

但我不知道如何在mysqli中做同样的事情。
当我运行以下代码时,它将显示以下错误。

Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in 

以下是我的代码。

if(isset($_REQUEST['term'])){
     // Prepare a select statement
     $sql = 'SELECT * FROM items WHERE (i_name LIKE ?) OR (i_code LIKE ?)';

     if($stmt = mysqli_prepare($ds, $sql)){
         // Bind variables to the prepared statement as parameters
         mysqli_stmt_bind_param($stmt, "s", $param_term);

         // Set parameters
         $param_term = $_REQUEST['term'] . '%';

         // Attempt to execute the prepared statement
         if(mysqli_stmt_execute($stmt)){
             $result = mysqli_stmt_get_result($stmt);

             // Check number of rows in the result set
             if(mysqli_num_rows($result) > 0){
                 // Fetch result rows as an associative array
                echo '<table class="table table-striped"><tbody><tr>';
                 while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

                    echo '<td width="70%">' . $row["i_name"] . '</td><td width="30%"><a href="edit-cat.php?cat='.$row['iid'].'"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</a></td>';
                 }
                echo '</tr></tbody></table>';
             } else{
                 echo "<p>No matches found</p>";
             }
         } else{
             echo "ERROR: Could not able to execute $sql. " . mysqli_error($ds);
         }
     }

     // Close statement
     mysqli_stmt_close($stmt);
 }

 // close connection
 mysqli_close($ds);
 ?>

的jQuery

<script>
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
$(document).ready(function(){
    $('.search-box input[type="text"]').on("keyup input", function(){
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length){
            $.get("search-item.php", {term: inputVal}).done(function(data){
                resultDropdown.html(data);
            });

        } else{
            resultDropdown.empty();
        }
    });
    $(document).on("click", ".result p", function(){
        $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

由于查询中有两个占位符,因此需要在mysqli_stmt_bind_param中使用两个变量。您可以两次使用相同的变量来绑定多个占位符。

mysqli_stmt_bind_param($stmt, "ss", $param_term, $param_term);