Search code examples
phpmysqlsecuritymysqliprepared-statement

When is it necessary to bind parameters with MySQLi?


From this code I received an error.

//Prepare insert statement.
if($InsertEventQuery = $mysqli->prepare("INSERT into events(eventname, eventdesc, eventmonth, eventdate, eventyear, eventstart, eventend) VALUES ('$EventName','$EventDesc','$EventMonth','$EventDate','$EventYear','$EventStart','$EventEnd')"))
{
    //Bind parameters of insert statement.
    $InsertEventQuery->bind_param('ssiiiii', $EventName, $EventDesc, $EventMonth, $EventDate, $EventYear, $EventStart, $EventEnd);

This is the error:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in[...]

I looked into it because the error appears to be incorrect and found:

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

You do not need to bind parameters in this case. Placeholders are used for the values in an INSERT statement, or in a WHERE clause. (Note that placeholders are not allowed for identifiers, such as the column names in your statement.)

This confused me and I am now wondering in interest of security, when is it necessary to bind parameters and when is it necessary to use placeholders.


Solution

  • Binding parameters is a good idea in any INSERT statement as it will prevent SQL injection, and will also sanitize your strings for free.

    I usually get it working using question mark in prepare statement like this:

    //Prepare insert statement.
    if ($InsertEventQuery = $mysqli->prepare("INSERT into events(eventname, eventdesc, eventmonth, eventdate, eventyear, eventstart, eventend) VALUES (?, ?, ?, ?, ?, ?, ?)"))
    {
        //Bind parameters of insert statement.
        $InsertEventQuery->bind_param('ssiiiii', $EventName, $EventDesc, $EventMonth, $EventDate, $EventYear, $EventStart, $EventEnd);