Prepared statements are very useful for preventing MySQL injection.
Prepared statements are used to execute multiple identical SQL statements more efficiently.
Prepared statements work as follows:
Preprocessing: Create SQL statement templates and send them to the database. Reserved values are marked with the parameter "?". For example:
INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)
Database parsing, compilation, query optimization on SQL statement templates, and storage of results without output.
Execution: Finally, the application-bound value is passed to the parameter ("?" mark), and the database executes the statement. The application can execute the statement multiple times if the parameter values are different.
Compared with directly executing SQL statements, prepared statements have two main advantages:
Prepared statements greatly reduce analysis time, as only one query is made (although the statement is executed multiple times).
Binding parameters reduces server bandwidth, you only need to send the parameters of the query instead of the entire statement.
Prepared statements are very useful for SQL injection because different protocols are used after parameter values are sent, ensuring the validity of the data.
The following example uses prepared statements in MySQLi and binds the corresponding parameters:
Parse each line of code for the following example:
"INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"In SQL statement, we use question mark (?), here we can replace question mark with integer, string, double precision floating point and boolean value.
Next, let's take a look at the bind_param() function:
$stmt->bind_param("sss", $firstname, $lastname, $email);This function binds SQL parameters and tells the database the value of the parameters. The "sss" parameter column handles the data types of the remaining parameters. The s character tells the database that the parameter is a string.
There are four types of parameters:
i - integer (integer type)
d - double (double precision floating point type)
s - string
b - BLOB (binary large object: binary large object)
Each parameter requires a specified type.
By telling the database the data type of the parameter, you can reduce the risk of SQL injection.
Note: If you want to insert other data (user input), validation of the data is very important. |
In the following example, we use prepared statements and bind parameters in PDO: