This article describes how to use mysqli extension to connect to the MySQL database in PHP. For more information, see section 1. object-oriented usage.
$db = new mysqli('localhost', 'root', '123456', 'dbname');
If no database is specified during connection establishment, select the database to use and switch to the database to be used.
$ Db-> select_db ('dbname'); $ query = "SELECT * FROM user WHERE uid = 4"; $ result = $ db-> query ($ query ); $ result_num = $ result-> num_rows; $ row = $ result-> fetch_assoc (); // returns an associated array, you can use $ row ['uid'] to obtain the value $ row = $ result-> fetch_row (); // return an array listing, you can get the value $ row = $ result-> fetch_array () through $ row [0]; // return a mixed array, you can use $ row ['uid'] or $ row [0] to obtain the value $ row = $ result-> fetch_object (); // return an object, you can get the value $ result-> free () through $ row-> uid; // release the result set $ db-> close (); // close a database connection, this is not necessary because the connection is automatically closed when the script is executed.
When performing INSERT, UPDATE, and DELETE operations, use $ db-> affected_rows to view the number of affected rows.
2. process-oriented usage
$db = mysqli_connect('localhost', 'root', '123456', 'dbname');
If no database is specified during connection establishment, select the database to use and switch to the database to be used.
mysqli_select_db($db, 'dbname');
Query a database
$query = "SELECT * FROM user WHERE uid=4";$result = mysqli_query($db, $query);$result_num = mysqli_num_rows($result);
Returns a row of results.
$ Row = mysqli_fetch_assoc ($ result); // returns an associated array. you can obtain the value $ row = mysqli_fetch_row ($ result) by using $ row ['uid ); // returns a list array. you can obtain the value $ row = mysqli_fetch_array ($ result) by using $ row [0]; // returns a mixed array, you can use $ row ['uid'] or $ row [0] to obtain the value $ row = mysqli_fetch_object ($ result); // return an object, you can get the value by $ row-> uid.
Disconnect a database
Mysqli_free_result ($ result); // release the result set mysqli_close ($ db); // closes a database connection. this is not necessary because the connection is automatically closed when the script is executed.
When performing INSERT, UPDATE, and DELETE operations, use mysqli_affected_rows () to view the number of affected rows.