This tutorial provides php beginners with an article about how to connect php to the mysql database and query and read/write the mysql database. If you need to learn, refer to the tutorial.
1. Connect to the database
Database variable file: connectvars. php
| The Code is as follows: |
Copy code |
<? Php
// Server
Define ('db _ host', '2017. 0.0.1 ');
// User Name
Define ('db _ user', 'root ');
// Password
Define ('db _ password', 'root ');
// Database
Define ('db _ name', 'test ');
?> |
Connect to the database in use
| The Code is as follows: |
Copy code |
|
Require_once 'connectvars. php ';
$ Dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ); |
2. add, delete, modify, and query Databases
// Query, modify, and delete operations are all written as SQL statements.
| The Code is as follows: |
Copy code |
$ Query = "SELECT * FROM toyota order by id desc ";
// $ Data stores a wealth of information and can be used to determine whether the operation is successful or use it to retrieve data and query the number of records
$ Data = mysqli_query ($ dbc, $ query ); |
Iii. Determine whether the operation is successful
| The Code is as follows: |
Copy code |
|
If ($ data ){
Echo 'data operation successful ';
} Else {
Echo 'data operation failed ';
} |
4. Obtain the number of query records
| The Code is as follows: |
Copy code |
|
$ Count = mysqli_num_rows ($ data );
Echo $ count; |
5. Perform cyclic operations on records
Assume that there is a field in the record as 'url'
| The Code is as follows: |
Copy code |
|
While ($ row = mysqli_fetch_array ($ data )){
Echo $ row ['url'];
} |