Search code examples
phpsqlcode-injection

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables when trying to secure query


I wanted to secure my php code from sql injections using the bind_param functions and I came across this error. I checked the amount of ?'s and bind_params but they are both equal, so I have no idea what I have done wrong.

I think this is the part the error comes from:

$conn = mysqli_connect($servername, $username, $password, $database);
$searchText = $_POST['search'];
echo "You searched for: " . htmlspecialchars($searchText, ENT_QUOTES, 'UTF-8');
$query = $conn->prepare("SELECT * FROM recources WHERE recource_title LIKE '%?%' OR recource_topic LIKE '%?%' OR recource_author LIKE '%?%' OR recource_description LIKE '%?%';");
$query->bind_param('s', $searchText, $searchText, $searchText, $searchText);
$query->execute();

Edit: I tried using $query->bind_param('ssss' instead of 1 s, but I still get this error.


Solution

  • You need to unquote your placeholders and concatenate the wildcards in the binding. Your error is because you have no placeholders in your query.

    Once you correct the placeholders you'll need to correct the binding call. The first parameter is what each variable being bound is so:

    bind_param('s'
    

    should really be

    bind_param('ssss'
    

    (because you have 4 variables) A Full example:

    $query = $conn->prepare("SELECT * FROM recources WHERE recource_title LIKE ? OR recource_topic LIKE ? OR recource_author LIKE ? OR recource_description LIKE ?;");
    $wild_var = '%' . $searchText . '%';
    $query->bind_param('ssss', $wild_var, $wild_var, $wild_var, $wild_var);
    $query->execute();