当前位置:网站首页>[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 .
边栏推荐
- 存在安全隐患 起亚召回部分K3新能源
- People help ant help task platform repair source code
- (十六)ADC转换实验
- vulnhub靶场-hacksudo - Thor
- Computed property “xxx“ was assigned to but it has no setter.
- RadHat搭建内网YUM源服务器
- 反射型XSS漏洞
- The reviewboard has 500 errors when submitting a review. Solutions
- ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
- PHP实现敏感词过滤系统「建议收藏」
猜你喜欢
Euler function: find the number of numbers less than or equal to N and coprime with n
Intel's open source deep learning tool library openvino will increase cooperation with local software and hardware parties and continue to open
New patent applications and transfers
Data warehouse (3) star model and dimension modeling of data warehouse modeling
GameFramework食用指南
Machine learning 11 clustering, outlier discrimination
The new server is packaged with the source code of H5 mall with an operation level value of several thousand
PETRv2:一个多摄像头图像3D感知的统一框架
In aks, use secret in CSI driver mount key vault
ACM MM 2022视频理解挑战赛视频分类赛道冠军AutoX团队技术分享
随机推荐
How to use JMeter function and mockjs function in metersphere interface test
【牛客网刷题系列 之 Verilog快速入门】~ 优先编码器电路①
vulnhub靶场-hacksudo - Thor
libcurl下载文件的代码示例
SLO is increasingly used to achieve observability | Devops
vulnhub靶场-Hacker_Kid-v1.0.1
开发那些事儿:EasyCVR集群设备管理页面功能展示优化
两数之和c语言实现[通俗易懂]
(17) DAC conversion experiment
SQL注入漏洞(Mysql与MSSQL特性)
GameFramework食用指南
PETRv2:一个多摄像头图像3D感知的统一框架
Radhat builds intranet Yum source server
ISO 27001 Information Security Management System Certification
PHP实现敏感词过滤系统「建议收藏」
Soft test network engineer full truth simulation question (including answer and analysis)
Develop those things: easycvr cluster device management page function display optimization
中国冰淇淋市场深度评估及发展趋势预测报告(2022版)
Is Huishang futures a regular futures platform? Is it safe to open an account in Huishang futures?
In depth Research Report on China's disposable sanitary products production equipment industry (2022 Edition)