[Deep Learning] Summary of operating mysql database with PHP

1. Extended classification of PHP database


1. The MySQL extension is designed for MySQL 4.1.3 or earlier and is an early extension for PHP to interact with the MySQL database. Since it does not support the new features of the MySQL database server and has poor security, it is not recommended to be used in project development. It can be replaced with the MySQLi extension.

2. The MySQLi extension is an enhanced version of the MySQL extension. It not only includes all the functional functions of the MySQL extension, but also can use the advanced features in the new version of MySQL. For example, multi-statement execution and transaction support, preprocessing methods completely solve SQL injection problems, etc. The MySQLi extension only supports the MySQL database. If you do not consider other databases , this extension is a very good choice.

3. PDO is the abbreviation of PHP Data Objects (data objects). It provides a unified API interface. As long as the DSN (data source) is modified, the interaction between PHP applications and different types of database servers can be realized.
 

2. Connect to the database.

1. Steps to operate the database through the MySQL class library

Establish a connection to MySQL - open the specified database - set the character set of the default client - execute the SQL query - release the character set - close the connection

3.ExplanationSQL language.

       After completing the database connection, you can operate the database through SQL statements. In the MySQLi extension, the mysqli_query() function is usually used to send SQL statements and obtain execution results. The function is declared as follows:

 $conn represents the database connection obtained through the mysqli_connect() function, and $sql represents the SQL statement. When the function executes a SELECT, SHOW, DESCRIBE, or EXPLAIN query, the return value is the query result set, while for other queries, true is returned on success and false on failure.

Use the mysql_query() function to execute SQL statements. The data manipulation methods mainly include 5 methods
    Query data: Use the select statement to implement the data query function.
    Display data: Use the select statement to display the query results of the data.
    Insert data: Use the insert into statement to insert data into the database.
    Update data: Use the update statement to update records in the database.
    Delete data: Use the delete statement to delete records in the database!

4. Processing result sets


1. When a SQL statement is executed through the mysqli_query() function, the returned result set cannot be used directly. You need to use a function to obtain information from the result set and save it as an array a>. The functions commonly used in MySQLi extensions to process result sets are shown in the table.

2. In the table enumeration function, the return values ​​of mysqli_fetch_all() and mysqli_fetch_array() support two forms: associative array and index array. The first parameter of the function represents the result set, and the second parameter is an optional parameter. , indicating the returned array form, its values ​​include MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH three constants, respectively representing associative arrays , index array, or both, The default value is MYSQLI_BOTH.
 

3. When you need to query all records at once, you can use the mysqli_fetch_all() function to achieve this.

$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

Then print it out through var_dump($data);.

5. Preprocessing statements.

1. What is preprocessing.

There is a prepared statement mechanism in the MySQLi extension. The principle is to pre-compile the template of the SQL statement and only transmit the changed data when executed. The following figure demonstrates the difference between prepared statements and traditional methods.

As can be seen from the figure, when PHP needs to execute SQL, the traditional way is to write the sent data and SQL together. In this way, each SQL needs to go through a cycle of analysis, compilation and optimization; while prepared statements only need to be compiled Once a user submits a SQL template, the update operation can be completed by sending relevant data during operation, which greatly improves operating efficiency and eliminates the need to consider grammatical problems caused by special characters (such as single quotes) contained in the data.
 

2. Preprocessing related functions.

a. The mysqi_prepare() function is used to preprocess a SQL statement to be executed. The function declaration is as follows: mysqli_stmt mysqli_prepare ( mysqli $link , string $query ) The parameter $link represents the database connection, and $query represents the SQL statement template. When the function is executed, the preprocessing object is returned successfully, and false is returned upon failure.

b. When writing a SQL statement template, the syntax is to replace the data part with "?" placeholders. The sample code is as follows:
 

Summary of PHP operation mysql database

一.开启Mysql数据库
1)php可以通过MySql函数库来操作数据库
开启mysql扩展
编辑Php配置文件php.ini
extension_dir="php/ext文件路径"
启动extension=mysqli选项 在php.ini文件内;

 
二.PHP操作Mysql数据库的步骤:
1.连接mysql数据库服务器
2.判断是否连接正确
3.选择数据库
4.设置字符集编码
5.准备并执行SQL语句
6.处理结果集
7.释放结果集资源,关闭数据库
 
三.具体操作mysql数据库
先要写头部header()汉字编码
如果数据库中有时间输出的话还要写时区类型
1.连接数据库
$conn=mysqli_connect(连接数据库的ip:3306,mysql数据库的账号,mysql数据库的密码)
2.判断是否连接成功
返回错误号
int mysql_errno([$link]); 中括号中的内容可以省略
如果为发生任何错误,此函数会返回0
返回错误信息
string mysqli_connect_error();
排查mysql数据库的错误信息可以用or die(...错误号.mysql_errno(),错误信息.mysqli_connect_error())来进行连接;
3.选择数据库
bool mysql_select_db('数据库的名字',[$link])
4.设置客户端汉字编码
bool mysql_set_charset('utf8',[$link])
5.执行SQL语句
mixed mysql_query(select(查看表内容)\show(tables查看数据库\
create tabel查看建表)\desc(查看表结构)\insert(添加记录)\
update(更新)\dalete(删除))
 
四.处理资源结果集
1.获取结果集包含的记录数目
int mysql_num_rows($表里记录信息变量)
2.获取表里的内容以索引数组返回值
array mysql_fetch_row($表里的记录信息变量)
3.获取表里的内容以关联数组返回值
array mysql_fetch_assoc($表里的记录信息变量)
4.获取结果集中字段的数目
int mysql_num_fieds($result)
5.返回结果集中某行记录的某个字段值(默认为首字段)
mysql_result($result, int $row)
int值是从0开始的0 拿某个字段的值
$row写字段名
 
五.处理非查询语句
1.获取插入时受影响行的行数
int mysql_affected_rows()
2.获取插入时最后插入记录的主键id
int mysql_insert_id()
 
六.释放结果集资源
1.如果是执行的事查询SQL语句查询后必须要释放资源
bool mysql_free_result();
2.使用完数据库后要关闭数据库
bool mysql_close();















<?php
$username=$_POST['usernm']; 
 
$password=$_POST['passwd']; #接收来自login.php传递的passwd值赋值到$password上
$conn=mysqli_connect("localhost","root","root","login"); #建立与数据库的连接
if (!$conn)
{
die("连接错误:". mysqli_connect_error());
} #判断和数据库是否连接正确
$sql="select * from laptop where user='$username' and password='$password'"; 
$res=mysqli_query($conn,$sql); #连接,执行sql语句
if (mysqli_fetch_array($res)!=0) #将传参转化为数组,判断用户输入的值是否和数据库指定的字段中的值是否相同,相同即不为0,不相同反之。
{
echo "OK"; #可以改成页面链接 如:"header("location:query.html");"
}
else
{
echo "NO";
}
 
 
?>

PHP operation database

(1) Connect to database


<?php

$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = 'dbali';

$conn = new mysqli($servername, $username, $password, $dbname); // 创建连接

// 检测连接
if ($conn->connect_error) 
{
    die("连接失败: " . $conn->connect_error);
} 

$conn->set_charset('utf8');	//查询前设置编码,防止输出乱码

echo "连接成功";
?>

Eight steps to connect database MYSQL with PHP

1. Link to the MySQL database mysqli_connect();
2. Determine whether the link is successful
3. Set the character set mysqli_set_charset
4. Select the database mysqli_select_db

5. Prepare the SQL statement select update insert delete
6. Execute the SQL statement
in Use the mysql_query() function to execute SQL statements in the select database. There are mainly 5 ways to operate the data
    Query data: Use the select statement to implement the data query function.
    Display data: Use the select statement to display the query results of the data.
    Insert data: Use the insert into statement to insert data into the database.
    Update data: Use the update statement to update records in the database.
    Delete data: Use the delete statement to delete records in the database!
7. Process the result set
8. Close the database and release resources

<?php
 $conn = mysqli_connect('localhost','root','root');
 if (!$conn) 
 {
 die("连接失败: " . $conn->connect_error);   
 //exit('数据库连接失败');
 }
  
 mysqli_set_charset($conn,'utf8');
 mysqli_select_db($conn,'count');
  
 $sql = "select * from count";
 $obj = mysqli_query($conn,$sql);
 $res = mysqli_fetch_array($obj);
 var_dump($res);
 mysqli_close($conn);
  
 ?> 

(2) Write the statement, execute the statement
   ① Code to execute the statement: $res = $conn->query()
   ② If What is executed is an add, delete, modify statement, and the value of $res is a Boolean value (insert, update, delete)
   ③ If a query statement is executed, the query result set (object) (select) is obtained a>
   ⑤ Close the database
   ④ If it is a query statement, remember to release the query result set to avoid wasting resources

Guess you like

Origin blog.csdn.net/zgscwxd/article/details/134980413