Home Backend Development PHP Problem How to query a MySQL database using PHP

How to query a MySQL database using PHP

Apr 13, 2023 am 09:20 AM

As a developer, we will inevitably come into contact with database applications at work. As for the language that completes database operations, PHP is undoubtedly the most widely used language. In PHP, using the MySQL database is one of the most common practices. This article mainly explains how to use PHP to query the MySQL database and gives the corresponding source code.

[Database Query]

First of all, we need to understand what a database query is. In MySQL, a query is an operation used to retrieve data from a database. Through queries, we can obtain the data stored in the database and use it for subsequent operations. Therefore, it is very necessary to know how to query the database.

In PHP, the process of querying the database is very simple. We only need to use some specific functions in the PHP program to query the data in the database. Next, let’s take a look at the specific steps.

[Steps]

  1. Connect to MySQL database

In PHP, we connect to MySQL database through two extensions, MySQLi and PDO. This article mainly uses the MySQLi extension to operate. The steps to connect to the MySQL database are as follows:

$servername = "localhost"; // 数据库所在服务器的名称
$username = "username"; // 用户名
$password = "password"; // 密码
$dbname = "myDB"; // 数据库名称

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

// 检查连接是否正常
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
Copy after login

The above code uses the mysqli_connect() function to create a connection. When the connection fails, we use the die() function to output an error message and stop the execution of the program.

  1. Execute query

After the connection is successful, we can start executing the query. In PHP, we use mysqli_query() function to execute queries. The following is an example of querying all data:

$sql = "SELECT * FROM MyGuests";
$result = $conn->query($sql);
Copy after login

In the above code, we use the SELECT statement to select all the data in the MyGuests table and save the results in the $result variable.

  1. Processing query results

The result of the query is usually a list containing multiple rows of data, and we need to process it row by row. The following is an example of traversing the query results and printing:

if ($result->num_rows > 0) {
    // 输出数据
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果。";
}
Copy after login

In the above code, we use the if statement to check whether the result list is empty. If it's not empty, use a while loop to iterate through the result list and print each row of data.

  1. Close the connection

When the query ends, we need to close the database connection. The following is the code to close the connection:

$conn->close();
Copy after login

[Source code]

The following is the complete code snippet for querying all data in the MyGuests table.

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

// 执行查询
$sql = "SELECT * FROM MyGuests";
$result = $conn->query($sql);

// 处理查询结果
if ($result->num_rows > 0) {
    // 输出数据
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果。";
}

// 关闭连接
$conn->close();
?>
Copy after login

[Summary]

In this article, we learned how to use PHP to query the MySQL database and provided the corresponding source code. Whether you are a novice or an experienced user, I hope this article will be helpful to your database query operations.

The above is the detailed content of How to query a MySQL database using PHP. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24