search
HomeBackend DevelopmentPHP ProblemHow to query a MySQL database using PHP

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

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

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 结果。";
}

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

[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();
?>

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

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool