PHP SQL Statement Preprocessing
Preface
After learning basic SQL statements, we need to add some parameters to the statements. If we use string concatenation directly, it is very easy to cause SQL injection, which affects data security. Therefore, we now need to preprocess SQL statements, setting the places to be filled as variables, so that no matter what, it will not be vulnerable to SQL injection.
Connection
1 | $mysql_server_name = '127.0.0.1'; |
Construction
When constructing SQL statements, we use ?
to fill in the places for variables.
1 | $sql = "SELECT * FROM `data` where `code`=? limit 1"; |
Binding Parameters
We bind the parameters to be filled to the SQL statement. Note the s
in the first line, where s
represents one string. If we want to bind multiple parameters at the same time, we need to write it as sss
, with as many s
as there are parameters.
1 | mysqli_stmt_bind_param($stmt, 's', $value); |
Retrieving Results
If it is a query statement, we need to retrieve the results obtained from the query. To get a specific result directly, use ['name']
.
1 | $result = mysqli_stmt_get_result($stmt); |