Php mysqli extension preprocessing and phpmysqli preprocessing
In the previous article about mysqli basic knowledge, I talked about mysqli installation and basic operations (mainly query operations for a single SQL statement). Today I will introduce a very important part of mysqli: preprocessing.
Mysqli operations often involve three main classes: MySQLi, MySQL_STMT, and MySQLi_RESULT. Preprocessing is mainly completed using the MySQL_STMT class.
Preprocessing is an important method to prevent SQL injection and is of great significance for improving website security.
In this case, the database name is "test", the data table name is "test", the fields are id and title, and the id is the auto-increment primary key.
Use mysqli preprocessing to perform the insert operation:
<? Php define ("HOST", "localhost"); define ("USER", 'root'); define ("PWD", ''); define (" DB ", 'test'); $ mysqli = new Mysqli (HOST, USER, PWD, DB); if ($ mysqli-> connect_errno) {"Connect Error :". $ mysqli-> connect_error;} $ mysqli-> set_charset ('utf8'); $ id = ''; $ title = 'title4'; // use? Replace variable $ SQL = "INSERT test VALUES (?,?) "; // Get the $ mysqli_stmt object. Remember to pass $ SQL. preprocessing is the preprocessing of SQL statements. $ Mysqli_stmt = $ mysqli-> prepare ($ SQL); // The first parameter indicates the variable type, including I (int), d (double), s (string ), B (blob) $ mysqli_stmt-> bind_param ('is', $ id, $ title); // execute the preprocessing statement if ($ mysqli_stmt-> execute ()) {echo $ mysqli_stmt-> insert_id;} else {echo $ mysqli_stmt-> error ;}$ mysqli-> close ();
Use mysqli preprocessing to prevent SQL injection:
$ Id = '4'; $ title = 'title4'; $ SQL = "SELECT * FROM test WHERE id =? AND title =? "; $ Mysqli_stmt = $ mysqli-> prepare ($ SQL); $ mysqli_stmt-> bind_param ('is', $ id, $ title ); if ($ mysqli_stmt-> execute () {$ mysqli_stmt-> store_result (); if ($ mysqli_stmt-> num_rows ()> 0) {echo "verified ";} else {echo "Verification Failed" ;}}$ mysqli_stmt-> free_result (); $ mysqli_stmt-> close ();
Use mysqli preprocessing to execute the query statement:
$ SQL = "SELECT id, title FROM test WHERE id >=? "; $ Mysqli_stmt = $ mysqli-> prepare ($ SQL); $ id = 1; $ mysqli_stmt-> bind_param ('I', $ id ); if ($ mysqli_stmt-> execute () {$ mysqli_stmt-> store_result ();
// Bind a variable to a prepared statement for result storage $ mysqli_stmt-> bind_result ($ id, $ title); while ($ mysqli_stmt-> fetch ()) {echo $ id. ':'. $ title. '<br/> ';}}
For more information about mysqli technology, see the official php Manual. The best way to learn is to query the manual ~