Table of Contents
Introduction
PHP MySQLi extension
Database connection and query
避免 SQL 注入攻击
插入记录到数据库
Home Topics php mysql MySQL database interaction with PHP Mysqli extension

MySQL database interaction with PHP Mysqli extension

Sep 07, 2020 am 09:20 AM
mysql mysqli php

MySQL database interaction with PHP Mysqli extension

[Related learning recommendations: php programming (video)]

Introduction

I have briefly introduced how to install MySQL locally and interact with the MySQL server through the command line and GUI client software.

You can interact with MySQL through commands on the command line, and you can interact with MySQL through the graphical interface on the client software. So how to establish a connection and interaction with MySQL in a PHP program? In fact, we can regard the PHP application as a client of the MySQL server, and then interact with the MySQL server through the API provided by the encapsulated PHP extension package, just like we do in the command line and client software , but now this interaction is changed from manual operation to completed by writing corresponding PHP code.

PHP MySQLi extension

PHP officially provides many extensions for interacting with the MySQL server, from the earliest mysql to the later enhanced version of mysqli (more secure), they are all PHP functions Extension packages in the era of formal programming. Generally speaking, the local PHP integrated development environment will come with mysqli extension:

MySQL database interaction with PHP Mysqli extension

Let’s use a simple example below To demonstrate how to interact with the MySQL server through the mysqli extension.

Database connection and query

Sample code

Add a new mysql in the php_learning directory subdirectory, then create a new mysqli.php file in the subdirectory, and write a piece of code to establish a database connection and query through the mysqli extended API:

<?php $host = &#39;127.0.0.1&#39;;   // MySQL 服务器主机地址
$port = 3306;          // MySQL 服务器进程端口号
$user = &#39;root&#39;;         // 用户名
$password = &#39;root&#39;;     // 密码
$dbname = &#39;test&#39;;       // 使用的数据库名称

// 通过 mysqli 扩展建立与 mysql 服务器的连接
$conn = mysqli_connect($host, $user, $password, $dbname, $port);

// 在连接实例上进行查询
$sql = &#39;SELECT * FROM `post`&#39;;
$res = mysqli_query($conn, $sql);

// 获取所有结果
$rows = mysqli_fetch_all($res);
var_dump($rows);

// 释放资源
mysqli_free_result($res);
// 关闭连接
mysqli_close($conn);
Copy after login

Yes As you can see, the connection to the MySQL database can be established through the mysqli_connect function. We pass in 5 parameters, which are database host, user name, password, database name and port number. After the connection is successfully established, you can hold the connection. The instance executes the database query through the mysqli_query function. We pass in the SQL statement as the second parameter. The return result of the function is a query result set instance. After getting this instance, you can use mysqli_fetch_* The series function obtains the result data.

Here we get all the query results through the mysqli_fetch_all function, and start the PHP built-in HTTP server through php -S localhost:9000:

MySQL database interaction with PHP Mysqli extension

You can print the query results in the browser through http://localhost:9000/mysql/mysqli.php:

MySQL database interaction with PHP Mysqli extension

Optimize the rendering effect

At this time, the readability of the page style is very poor. You can insert a section of echo '<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'# before printing the output result in the source code. ## Code optimization rendering effect: </pre><div class="contentsignin">Copy after login</div></div>

// 获取所有结果
$rows = mysqli_fetch_all($res);
echo '<pre class="brush:php;toolbar:false">';
var_dump($rows);
Copy after login
Refresh the browser page, you can see the following printing effect:

MySQL database interaction with PHP Mysqli extension

Related learning recommendations:

mysql tutorial(Video)

Set character encoding

There is a small problem here, that is, the Emoji emoticons are not displayed properly. The characters are garbled. We can set the character encoding to

utf8mb4 through the mysqli_set_charset function just like setting the default character encoding on the command line:

// 通过 mysqli 扩展建立与 mysql 服务器的连接
$conn = mysqli_connect($host, $user, $password, $dbname, $port);
// 设置字符编码为 utf8mb4
mysqli_set_charset($conn, 'utf8mb4');

...

// 获取所有结果
$rows = mysqli_fetch_all($res);
echo '<pre class="brush:php;toolbar:false">';
var_dump($rows[2]);
Copy after login
Refresh the page and you can see the Emoji expression:

MySQL database interaction with PHP Mysqli extension

Return to associative array

The currently returned result is an index array, and the field name corresponding to the value cannot be known. To obtain the complete field Name and field value mapping can be achieved by setting the second parameter value passed into the

mysqli_fetch_all function to MYSQLI_ASSOC (the default is MYSQLI_NUM):

// 获取所有结果(关联数组)
$rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
echo '<pre class="brush:php;toolbar:false">';
var_dump($rows[2]);
Copy after login

MySQL database interaction with PHP Mysqli extension

Return a single result

All the results returned above are multiple results (even if only one record is returned, the returned result is a multi-dimensional array), Sometimes, we only want to return the first result in the result set. This can be achieved through the mysqli_fetch_row function:

// 在连接实例上进行查询
$sql = 'SELECT * FROM `post` WHERE id = 1';
$res = mysqli_query($conn, $sql);

// 获取所有结果
/*
$rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
echo '<pre class="brush:php;toolbar:false">';
var_dump($rows);*/

// 获取单条结果
$row = mysqli_fetch_row($res);
echo '<pre class="brush:php;toolbar:false">';
var_dump($row);
Copy after login
Refresh the browser test page and print the results as follows:

MySQL database interaction with PHP Mysqli extension

可以看到返回结果已经是一个一维数组了,只包含一条记录。如果想要返回关联数组结果,需要通过一个新的函数 mysqli_fetch_assoc 函数来实现:

// 获取单条结果
// $row = mysqli_fetch_row($res);
$row = mysqli_fetch_assoc($res);
echo '<pre class="brush:php;toolbar:false">';
var_dump($row);
Copy after login

对应的打印结果如下:

MySQL database interaction with PHP Mysqli extension

将返回结果映射到指定对象

除了返回数组格式结果外,还可以借助 mysqli_fetch_object 函数将数据库查询结果映射到指定对象实例并返回:

class Post
{
    public $id;
    public $title;
    public $content;
    public $created_at;

    public function __toString()
    {
        return '[#' . $this->id . ']' . $this->title;
    }
}
// 将数据库返回结果映射到指定个对象
$post = mysqli_fetch_object($res, Post::class);
echo $post;
Copy after login

对应的打印结果如下,说明对象映射成功(调用了对象的魔术方法 __toString 打印输出该对象):

MySQL database interaction with PHP Mysqli extension

避免 SQL 注入攻击

在上述数据库查询操作中,我们直接将原生 SQL 语句传递给 MySQL 数据库执行,如果 SQL 语句中包含了用户传递的参数,则存在 SQL 注入风险,要避免 SQL 注入攻击,在 mysqli 扩展中,可以通过构建预处理语句的方式实现:

  1. 首先通过 mysqli_prepare 函数构建包含占位符(替代具体参数值)的预处理 SQL 语句;
  2. 然后通过 mysqli_stmt_bind_param 函数将参数值绑定到预处理语句;
  3. 最后通过 mysqli_stmt_execute 函数执行填充参数值之后的完整 SQL 语句,由于底层做了转化处理,所以这时候执行的 SQL 语句不存在 SQL 注入风险。

下面,我们以插入记录到数据库为例,演示如何通过预处理语句的方式与数据库交互,提高代码安全性。

插入记录到数据库

我们首先基于预处理语句编写插入记录到数据库的代码如下(基于上面的 $conn 连接实例):

// 插入记录到数据库
$sql = 'INSERT INTO `post` (title, content, created_at) VALUES (?, ?, ?)';
// 构建预处理 SQL 语句
$stmt = mysqli_prepare($conn, $sql);

// 绑定参数值
$title = '这是一篇测试文章';
$content = '测试文章啊啊啊
Copy after login

The above is the detailed content of MySQL database interaction with PHP Mysqli extension. For more information, please follow other related articles on the PHP Chinese website!

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 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)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles