Home Backend Development PHP Tutorial PHP连接和操作MySQL数据库基础教程_php实例

PHP连接和操作MySQL数据库基础教程_php实例

May 16, 2016 pm 08:35 PM
mysql php operate database connect

从这里开始

我的博客,后台数据库是什么?没错,就是MySQL,服务器端使用的脚本就是PHP,整个框架使用的是WordPress。PHP和MySQL就像夫妻一样,总是在一起干活。现在这里,就集合PHP,总结一下MySQL的实际使用,也算作是MySQL开发的入门。关于PHP与MySQL的合作,不外乎以下三种方法:

1.mysql扩展;但是目前已经不推荐使用;

2.mysqli扩展;同时提供面向对象风格和面向过程的风格;要求MySQL版本是4.1及以上的;

3.PDO扩展为PHP访问数据库定义了一种轻量级的一致接口;PDO_MYSQL是对其的具体实现。这里暂时只关心开发。由于mysql扩展已经不推荐使用了,我也会与时俱进,不做总结;而mysqli和PDO方式用的比较多,所以这篇将会总结如何使用mysqli扩展来连接数据库服务器,如何查询和获取数据,以及如何执行其它重要任务。下一篇博文将会总结PDO的相关内容。

使用mysqli扩展

先看以下测试数据库db_test中的测试数据:

复制代码 代码如下:

mysql> select * from tb_test;
+----+-----------+----------+------------+------------+
| id | firstname | lastname | email      | phone      |
+----+-----------+----------+------------+------------+
|  1 | Young     | Jelly    | 123@qq.com | 1384532120 |
|  3 | Fang      | Jone     | 456@qq.com | 1385138913 |
|  4 | Yuan      | Su       | 789@qq.com | 1385138913 |
+----+-----------+----------+------------+------------+
3 rows in set (0.00 sec)

1.建立和断开连接

与MySQL数据库交互时,首先要建立连接,最后要断开连接;这包括与服务器连接并选择一个数据库,以及最后关闭连接,释放资源。选择使用面向对象接口与MySQL服务器交互,首先需要通过其构造函数实例化mysqli类。

复制代码 代码如下:

    // 实例化mysqli类
    $mysqliConn = new mysqli();
    // 连接服务器,并选择一个数据库
    $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
    printf("MySQL error number:%d", $mysqliConn->errno);
    // 或者
    // $mysqliConn->connect("http://127.0.0.1", 'root', 'root');
    // $mysqliConn->select_db('db_test');
   
    // 与数据库交互
   
    // 关闭连接
    $mysqliConn->close();
?>

一旦成功的选择了数据库,然后就可以对这个数据库执行数据库查询了。一旦脚本执行完毕,所有打开的数据库连接都会自动关闭,并释放资源。不过,有可能一个页面在执行期间需要多个数据库连接,各个连接都应当适当的加以关闭。即使只使用一个连接,也应该在脚本的最后将其关闭,这是一种很好的实践方法。在任何情况下,都由close()负责关闭连接。

2.处理连接错误

当然,如果无法连接MySQL数据库,那么不大可能在这个页面继续完成预期的工作了。因此,一定要注意监视连接错误并相应地做出反应。mysqli扩展包包含很多可以用来捕获错误消息的特性,另外也可以使用异常来做到这一点。例如,可以使用mysqli_connect_errno()和mysqli_connect_error()方法诊断并显示一个MySQL连接错误的有关信息。

关于mysqli的具体信息可以在这里查看:http://php.net/manual/zh/book.mysqli.php

与数据库交互

绝大多数查询都与创建、获取、更新和删除任务有关,这些任务统称为CRUD。这里就开始总结CRUD相关的内容。

1.向数据库发送查询

方法query()负责将query发送给数据库。它的定义如下:

复制代码 代码如下:

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

可选参数resultmode可以用于修改这个方法的行为,它接受两个可取值。这篇文章总结了二者之间的区别。http://www.jb51.net/article/55792.htm;下面是一个简单的使用例子:

复制代码 代码如下:

    // 实例化mysqli类
    $mysqliConn = new mysqli();
 
    // 连接服务器,并选择一个数据库
    // 错误的密码
    $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
    if ($mysqliConn->connect_error)
    {
        printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
        exit();
    }
   
    // 与数据库交互
    $query = 'select firstname, lastname, email from tb_test;';
 
    // 发送查询给MySQL
    $result = $mysqliConn->query($query);
 
    // 迭代处理结果集
    while (list($firstname, $lastname, $email) = $result->fetch_row())
    {
        printf("%s %s's email:%s
", $firstname, $lastname, $email);
    }
   
    // 关闭连接
    $mysqliConn->close();
?>

2.插入、更新和删除数据

插入、更新和删除使用的是insert、update和delete查询完成的,其做法实际上与select查询相同。示例代码如下:

复制代码 代码如下:

    // 实例化mysqli类
    $mysqliConn = new mysqli();
 
    // 连接服务器,并选择一个数据库
    // 错误的密码
    $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
    if ($mysqliConn->connect_error)
    {
        printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
        exit();
    }
   
    // 与数据库交互
    $query = 'select firstname, lastname, email from tb_test;';
    // 发送查询给MySQL
    $result = $mysqliConn->query($query);
 
    // 迭代处理结果集
    while (list($firstname, $lastname, $email) = $result->fetch_row())
    {
        printf("%s %s's email:%s
", $firstname, $lastname, $email);
    }
   
    $query = "delete from tb_test where firstname = 'Yuan';";
    $result = $mysqliConn->query($query);
 
    // 告诉用户影响了多少行
    printf("%d row(s) have been deleted.
", $mysqliConn->affected_rows);
    // 重新查询结果集
    $query = 'select firstname, lastname, email from tb_test;';
 
    // 发送查询给MySQL
    $result = $mysqliConn->query($query);
 
    // 迭代处理结果集
    while (list($firstname, $lastname, $email) = $result->fetch_row())
    {
        printf("%s %s's email:%s
", $firstname, $lastname, $email);
    }
    // 关闭连接
    $mysqliConn->close();
?>

3.释放查询内存

有时可能会获取一个特别庞大的结果集,此时一旦完成处理,很有必要释放该结果集所请求的内存。free()方法可以为我们完成这个任务。例如:

复制代码 代码如下:

// 与数据库交互
$query = 'select firstname, lastname, email from tb_test;';
 
// 发送查询给MySQL
$result = $mysqliConn->query($query);
 
// 迭代处理结果集
while (list($firstname, $lastname, $email) = $result->fetch_row())
{
    printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
$result->free();

4.解析查询结果

一旦执行了查询并准备好结果集,下面就可以解析获取到的结果行了。你可以使用多个方法来获取各行中的字段,具体选择哪一个方法主要取决于个人喜好,因为只是引用字段的方法有所不同。

(1)将结果放到对象中

使用fetch_object()方法来完成。fetch_object()方法通常在一个循环中调用,每次调用都使得返回结果集中的下一行被填入一个对象,然后可以按照PHP典型的对象访问语法来访问这个对象。例如:

复制代码 代码如下:

// 与数据库交互
$query = 'select firstname, lastname, email from tb_test;';
 
// 发送查询给MySQL
$result = $mysqliConn->query($query);
 
// 迭代处理结果集
while ($row = $result->fetch_object())
{
    $firstname = $row->firstname;
    $lastname = $row->lastname;
    $email = $row->email;
}
$result->free();

(2)使用索引数组和关联数组获取结果

mysqli扩展包还允许通过fetch_array()方法和fetch_row()方法分别使用关联数组和索引数组来管理结果集。fetch_array()方法实际上能够将结果集的各行获取为一个关联数组、一个数字索引数组,或者同时包括二者,可以说,fetch_row()是fetch_array的一个子集。默认地,fetch_array()会同时获取关联数组和索引数组,可以在fetch_array中传入参数来修改这个默认行为。

MYSQLI_ASSOC,将行作为一个关联数组返回,键由字段名表示,值由字段内容表示;
MYSQLI_NUM,将行作为一个数字索引数组返回,其元素顺序由查询中指定的字段名顺序决定;
MYSQLI_BOTH,就是默认的选项。

确定所选择的行和受影响的行

通常希望能够确定select查询返回的行数,或者受insert、update或delete影响的行数。

(1)确定返回的行数

如果希望了解select查询语句返回了多少行,num_rows属性很有用。例如:

复制代码 代码如下:

// 与数据库交互
$query = 'select firstname, lastname, email from tb_test;';
 
// 发送查询给MySQL
$result = $mysqliConn->query($query);
 
// 获取行数
$result->num_rows;

记住,num_rows只在确定select查询所获取的行数时有用,如果要获得受insert、update或delete影响的行数,就要使用下面总结的affected_rows属性。

(2)确定受影响的行数

affected_rows属性用来获取受insert、update或delete影响的行数。代码示例见上面的代码。

执行数据库事务

有3个新方法增强了PHP执行MySQL事务的功能,分别为:

1.autocommit函数,启用自动提交模式;

autocommit()函数控制MySQL自动提交模式的行为,由传入的参数决定启动还是禁用自动提交;传入TRUE,则启动自动提交,传入false则禁用自动提交。无论启用还是禁用,成功时都将返回TRUE,失败时返回FALSE。

2.commit函数,提交事务;将当前事务提交给数据库,成功时返回TRUE,否则返回FALSE。

3.rollback函数,回滚当前事务,成功时返回TRUE,否则返回FALSE。

关于事务,我后面还要继续总结,这里就简要的总结了一下这三个API。

不会结束

这只是MySQL学习的开始,不会结束。再接再励。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

MongoDB's Future: The State of the Database MongoDB's Future: The State of the Database Apr 25, 2025 am 12:21 AM

MongoDB's future is full of possibilities: 1. The development of cloud-native databases, 2. The fields of artificial intelligence and big data are focused, 3. The improvement of security and compliance. MongoDB continues to advance and make breakthroughs in technological innovation, market position and future development direction.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

See all articles