当前位置:网站首页>[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 .
边栏推荐
- Source code of new campus errand / campus task platform on mutual station
- Rotation order and universal lock of unity panel
- 股票万1免5证券开户是合理安全的吗,怎么讲
- The reviewboard has 500 errors when submitting a review. Solutions
- In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
- C language implementation of sum of two numbers [easy to understand]
- 字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化
- Is it safe to open a stock account by mobile phone? What do you need to bring with you to open an account?
- Why should you consider using prism
- Cookies and session keeping technology
猜你喜欢

National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report
![[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①](/img/24/23f6534e2c74724f9512c5b18661b6.png)
[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①

Intel's open source deep learning tool library openvino will increase cooperation with local software and hardware parties and continue to open

Gold, silver and four want to change jobs, so we should seize the time to make up
![Integer array merge [JS]](/img/0d/70535e0eb1c299bda25159b58c70d7.png)
Integer array merge [JS]

GameFramework食用指南

How to use JMeter function and mockjs function in metersphere interface test

(十六)ADC转换实验

重磅披露!上百个重要信息系统被入侵,主机成为重点攻击目标

Product service, operation characteristics
随机推荐
(1) CNN network structure
National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report
Wechat applet blind box - docking wechat payment
unity3d扩展工具栏
libcurl下载文件的代码示例
New patent applications and transfers
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
vulnhub靶场-Hacker_Kid-v1.0.1
Intelligent operation and maintenance practice: banking business process and single transaction tracking
Reflective XSS vulnerability
(12) About time-consuming printing
In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
New 95 community system whole station source code
Euler function: find the number of numbers less than or equal to N and coprime with n
为什么你要考虑使用Prisma
JDBC: deep understanding of Preparedstatement and statement[easy to understand]
Report on research and investment prospects of China's silicon nitride ceramic substrate industry (2022 Edition)
剑指 Offer 20. 表示数值的字符串
Heavy disclosure! Hundreds of important information systems have been invaded, and the host has become a key attack target
中国乙腈市场预测与战略咨询研究报告(2022版)