PHP development basic tutorial database connection steps
We have organized the database connection into the 8 most important steps for you.
The eight steps are as follows, and the functions used in each step are explained:
Step 1: Connect to the database server
If parameter 4 and database name have been filled in and selected in this step, there is no need to perform the third step.
Step 2: Determine the error
Step Three: Select Database
If the database has been filled in in the first step and does not need to be changed to another database, there is no need to perform the third step. step.
Step 4: Set character set
Step 5: Prepare SQL statement
is actually a string of SQL statements.
For example:
$sql = "insert into user(username,password) values('$username','$password')";
We usually assign variables for use in SQL statements. However, there is an error in the variable or SQL statement, which is very difficult to troubleshoot.
We have added this step based on actual work experience.
If an error is reported when executing this step, we can print out the SQL statement and paste it into phpMyAdmin or related tools.
When troubleshooting, if the execution is successful, it means that the problem is not with the SQL statement. If execution fails, carefully check the SQL statement.
Step 6: Send the SQL statement
The SQL statement is ready and needs to be passed mysqli_query sends SQL statements to the MySQL server.
The MySQL server will execute the SQL statement sent.
Step 7: Determine whether the execution is normal or traverse the data
Read
In step 6, a statement of the select category is sent, and the result output usually needs to be displayed. You need to use the function that traverses the display data.
##Write
Step 6 , if you send an insert statement, you usually need to get whether the execution is successful, or get the auto-incremented ID at the same time.Modify and delete
In step 6, if the update and delete categories are sent statement. Just need to determine whether the execution is successful. We list the data tables of these commonly used functions for everyone to check.Step 8: Close the database
The database connection is a resource type. We told you about it when we explained resource types in the previous chapter. All resource types involved are either opened or closed. This ensures that PHP processes and recycles resources more efficiently. Therefore, after the database connection is successful, there is no need to use it. We can close this connection.Others: Display server information function
Note:mysqli only learns A procedural approach is sufficient. In the actual work of the object-oriented stage, the object usage of mysqli was completely abandoned, and instead the PDO object was used to connect to the database.