May 11, 2021 PHP
1. PHP MySQL preprocessing statement
2. Preprocess statements and binding parameters
3. MySQLi preprocessing statement
4. Instance (MySQLi uses preprocessed statements)
Preprocessed statements are useful for preventing MySQL injection.
Preprocessed statements are used to execute multiple identical SQL statements and are more efficient.
Preprocessed statements work as follows:
Preprocessing: Create a SQL statement template and send it to the database. T he reserved value is marked with the parameter "?" . For example: INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)
Database analysis, compilation, query optimization of SQL statement templates, and storage results are not output
Execution: Finally, the value of the applied binding is passed to the parameter (the "?" tag) and the database executes the statement. The app can execute statements multiple times if the value of the argument is different.
Preprocessed statements have two main advantages over executing SQL statements directly:
Preprocessed statements significantly reduce analysis time and make only one query (although statements are executed multiple times)
Binding parameters reduce server bandwidth, and you only need to send the parameters of the query, not the entire statement
Preprocessed statements are useful for SQL injection because parameter values are sent using different protocols to ensure the legitimacy of the data.
The following example uses a preprocessed statement in MySQLi and binds the appropriate parameters:
Resolve each line of code for the following instances:
In sql statements, we use question marks (?), where we can replace them with integers, strings, double floats, and Boolean values.
Next, let's look at bind_param() function:
The function binds the parameters of SQL and tells the value of the database parameters. T he "sss" parameter column handles the data types of the remaining parameters. The s character tells the database that the argument is a string.
There are four types of parameters:
i - integer (integer)
d - double (double floating-point type)
s - string (string)
b - BLOB (Boolean value)
Each parameter needs to specify a type.
You can reduce the risk of SQL injection by telling the data types of database parameters.
Note: If you want to insert additional data (user input), validation of the data is very important. |
The following examples we use in PDO to preprocess statements and bind parameters: