PHP uses mysqli to connect to the MySQL database and uses the mysqli function library to connect to MySQL. object-oriented and process-oriented methods are supported:
1. object-oriented usage
Create a connection
$ Db = new mysqli ('localhost', 'root', '123', '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 a database
$ Query = "SELECT * FROM user WHERE uid = 4 ";
$ Result = $ db-> query ($ query );
Count the number of rows returned
$ Result_num = $ result-> num_rows;
Returns a row of results.
$ Row = $ result-> fetch_assoc (); // returns an associated array, which can be obtained through $ row ['uid '].
$ Row = $ result-> fetch_row (); // returns a list array, which can be obtained through $ row [0 ].
$ Row = $ result-> fetch_array (); // returns a mixed array. values can be obtained through $ row ['uid'] or $ row [0 ].
$ Row = $ result-> fetch_object (); // returns an object, which can be obtained through $ row-> uid
Disconnect a database
$ Result-> free (); // release the result set
$ Db-> close (); // closes a database connection. this is not necessary because the connection is automatically closed when the script is executed.
In addition:
When performing INSERT, UPDATE, and DELETE operations, use $ db-> affected_rows to view the number of affected rows.
2. process-oriented usage
Create a connection
$ Db = mysqli_connect ('localhost', 'root', '123', '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 );
Count the number of rows returned
$ Result_num = mysqli_num_rows ($ result );
Returns a row of results.
$ Row = mysqli_fetch_assoc ($ result); // returns an associated array, which can be obtained through $ row ['uid '].
$ Row = mysqli_fetch_row ($ result); // returns a list array, which can be obtained by $ row [0 ].
$ Row = mysqli_fetch_array ($ result); // returns a mixed array. values can be obtained through $ row ['uid'] or $ row [0 ].
$ Row = mysqli_fetch_object ($ result); // returns an object, which can be obtained through $ 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.
In addition:
When performing INSERT, UPDATE, and DELETE operations, use mysqli_affected_rows () to view the number of affected rows.