当前位置:网站首页>[PHP foundation] realize the connection between PHP and SQL database
[PHP foundation] realize the connection between PHP and SQL database
2022-07-01 17:39:00 【Fighting_ hawk】
Catalog
1 Preface
- In order to realize the function of web page accessing background database , You need to connect it with the corresponding database in the web page code .
- PHP 5 And above, we recommend the following ways to connect MySQL :
- MySQLi extension (“i” Meaning for improved).
- PDO (PHP Data Objects).
- Comparison of two connection modes :
- PDO Apply to 12 In different databases , MySQLi Only aim at MySQL database .
- If the project needs to switch between multiple databases , It is recommended to use PDO , In this way, you only need to modify the connection string and some query statements . If you use MySQLi Connecting to different databases , You need to rewrite all the code , Including inquiries .
- Both are object-oriented , but MySQLi It also provides API Interface .
- Both support preprocessing statements . Preprocessing statements can prevent SQL Inject , about web The security of the project is very important .
- This section introduces the implementation of PHP And SQL The whole process of connection , This paper mainly introduces MySQLi Method .
2 Realization PHP Connect SQL The whole process of database experiment
2.1 Experimental environment
- Server side : This experiment is based on virtual machine win2008 Systematic WAMP Environment , Refer to the article for the configuration process related to this environment 《win2008R2SP1+WAMP The deployment environment 》.
- client : Use the browser to access and control .
- The server and the client are under the same LAN , Open the server phpstudy And make sure you can access... From the client browser .
2.2 Create database
- Log in through the browser on the client phpMyAdmin, The location is located in... Under the default root directory of the website phpMyAdmin Under the folder , Enter the target in the browser “IP+/phpMyAdmin” Visit , The default account passwords are root.

- After logging in, you can see the following interface , On the left is the default 4 A database . Click the database shown by the arrow , Get into .

- Create a new learning test database , Name it my_test, Type selection is “utf8_genrral_ci”, Click Create .

- Once created , You can see the created database here on the left . Click the database to enter .

- After entering, you can see that there are no forms in the database .

- Create a data table , Name it users, It is mainly used to store user information (id name password photo money) common 5 A field . Enter the following information and click execute .

- Create these fields ,id name password photo money, And set the type and length of the response , take id Set key as primary key .( The primary key must be non empty ).

- You can click on the left side to create a new users surface , The detailed structure information of this table is shown in the figure below .

2.3 insert data
- Click on SQL Enter the table modification interface , available SQL Statement execution .

- Modify the command as follows and click execute . Note that the symbol is in English format .
INSERT INTO `users`( `name`, `password`,`photo`, `money`) VALUES ("libai",123456,"./touxiang.jpg",100);
INSERT INTO `users`( `name`, `password`,`photo`, `money`) VALUES (" Li Bai ",123456,"./touxiang.jpg",100);
- Click on the left users surface , You can see the user information we entered . Here we enter libai And Li Bai , As shown in the figure below .

2.4 Realization PHP Interacting with the database
2.4.1 Realization PHP Interact with the database in three steps
1. Establishing a connection . When a user establishes a connection , You need to provide a user name + password + Address + Database name , The database name can be switched during connection .
2. perform SQL sentence .
3. disconnect .
2.4.2 Code 1 : Simple implementation of three steps
Simply realize the three steps of interaction , And feedback information according to whether the connection is successfully established . Visit this page to get the results
<?php
$dbHost = "127.0.0.1"; // Database address
$dbUser = "root"; // The direct assignment here is root, The actual use should be that the user logs in and enters his own account .
$dbPass = "root"; // The direct assignment here is root, The actual use should be that the user logs in and enters his own password .
$dbName = "my_test";
$link = @mysqli_connect($$dbHost,$dbUser,$dbPass,$dbName);// Establishing a connection , No display notice Information
if (!$link)
{
echo mysqli_connect_error();} // If the connection cannot be established, an error message is displayed .
$sql = "select * from users"; // Define the statement to execute .
$results = mysqli_query($link,$sql); // Execute the statement to get data from the connection .
var_dump($results); // Check the type of data obtained .
// The output of web pages is object type :object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(5) ["lengths"]=> NULL ["num_rows"]=> int(2) ["type"]=> int(0) }
mysqli_close($link); // disconnect
?>
2.4.3 Code 2 : Optimize code one
Based on code one , Get the data branch execution according to whether the statement is successfully executed , If successful, print the obtained data information in turn , If yes, an error prompt will be displayed . The result of browser access code 2 is shown in Figure , Among them, Chinese is garbled .
<?php
$dbHost = "127.0.0.1";
$dbUser = "root";
$dbPass = "root";
$dbName = "my_test";
$link = @mysqli_connect($$dbHost,$dbUser,$dbPass,$dbName);
if (!$link)
{
echo mysqli_connect_error();}
$sql = "select * from users";
if ($results = mysqli_query($link,$sql)){
//mysqli_query When the function fails to execute, it returns false, adopt mysqli_query() Successful execution SELECT, SHOW, DESCRIBE or EXPLAIN The query will return a mysqli_result object , Other queries return true.
while ($result = mysqli_fetch_assoc($results)){
// Use mysqli_fetch_assoc Function to get the specific data in the return object .
var_dump($result);
echo "<hr/>";
}
}
else{
die(mysqli_error($link));
}
mysqli_close($link);
?>

2.4.4 Code three : Change the connection mode to object-oriented
The main difference between object-oriented connection and process oriented in code one and two is , Connection process 、 The judgment process 、 The difference in the disconnection process . The process of data access and use is basically the same .
<?php
$dbHost = "127.0.0.1";
$dbUser = "root";
$dbPass = "root";
$dbName = "my_test";
$link = @new mysqli($$dbHost,$dbUser,$dbPass,$dbName);
if ($link->connect_error)
{
echo $mysqli->connect_error;}
$sql = "select * from users";
if ($results = mysqli_query($link,$sql)){
//mysqli_query When the function fails to execute, it returns false, adopt mysqli_query() Successful execution SELECT, SHOW, DESCRIBE or EXPLAIN The query will return a mysqli_result object , Other queries return true.
while ($result = mysqli_fetch_assoc($results)){
// Use mysqli_fetch_assoc Function to get the specific data in the return object .
var_dump($result);
echo "<hr/>";
}
}
else{
die(mysqli_error($link));
}
$link->close();
?>
3 Introduction to correlation function
3.1 Database connection operation related functions
| Function name | effect |
|---|---|
| new mysqli() mysqli_connect() | Connect to the specified database |
| $mysqli->connect_errno mysqli_connect_errno() | Return the error code of the last connection call |
| $mysqli->connect_error mysqli_connect_error() | Returns the error code of the last connection call described by a string |
| $link->close() mysqli_close($link) | disconnect , among $link Indicates the established connection . |
3.2 Operation result set object correlation function
| function | effect |
|---|---|
| mysqli_fetch_row() | Get the data of a record by index array |
| mysqli_fetch_assoc() | Get the data of a record in the way of associative array |
| mysqli_fetch_array() | Get the data of a record by indexing array or associative array |
| mysqli_fetch_all() | Get the data of all records by indexing the genus pig or associative array |
| mysqli_num_rows() | Get the number of rows in the result |
| mysqli_free_result() | Freeing memory associated with a result set |
3.3 More orders
For more orders, please refer to the official manual 《MySQL Enhanced extensions 》.
4 summary
- master phpstudy Operation mode of database in ;
- master PHP And MySQL Database connection and use ;
- Master common commands ;
- Understand the differences between object-oriented and process oriented connection ;
- Understand the general content of the official manual .
边栏推荐
- Kia recalls some K3 new energy with potential safety hazards
- 字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化
- Wechat applet blind box - docking wechat payment
- PHP实现敏感词过滤系统「建议收藏」
- [beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
- Leetcode records - sort -215, 347, 451, 75
- In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
- Htt [ripro network disk link detection plug-in] currently supports four common network disks
- 整形数组合并【JS】
- [C language foundation] 12 strings
猜你喜欢

走进微信小程序

Soft test network engineer full truth simulation question (including answer and analysis)

People help ant help task platform repair source code

(17) DAC conversion experiment

Vulnhub range hacksudo Thor

Product service, operation characteristics

Gameframework eating guide

Euler function: find the number of numbers less than or equal to N and coprime with n
荣威 RX5 的「多一点」产品策略

Gold, silver and four job hopping, interview questions are prepared, and Ali becomes the champion
随机推荐
Report on research and investment prospects of China's silicon nitride ceramic substrate industry (2022 Edition)
多线程使用不当导致的 OOM
In aks, use secret in CSI driver mount key vault
GameFramework食用指南
Soft test network engineer full truth simulation question (including answer and analysis)
中国乙腈市场预测与战略咨询研究报告(2022版)
【splishsplash】关于如何在GUI和json上接收/显示用户参数、MVC模式和GenParam
Gold, silver and four job hopping, interview questions are prepared, and Ali becomes the champion
National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report
Enter wechat applet
MySQL learning summary
China metallocene polyethylene (MPE) Industry Research Report (2022 Edition)
可迭代对象与迭代器、生成器的区别与联系
DRF --- response rewrite
ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
China acetonitrile market forecast and strategic consulting research report (2022 Edition)
Machine learning 11 clustering, outlier discrimination
Mysql database - Advanced SQL statement (2)
[C language supplement] judge which day tomorrow is (tomorrow's date)
深度优先遍历和广度优先遍历[通俗易懂]