Home  >  Article  >  Backend Development  >  How to write PHP query data

How to write PHP query data

PHPz
PHPzOriginal
2023-04-21 10:01:37701browse

In modern computer systems, the use of databases for data storage has become a very important part. As a common Web programming language, PHP provides us with many functions and tools for operating databases.

Querying data is an important part of database operations. This article will introduce how to use PHP to query data.

First of all, the core query statement is SELECT. It can be used to retrieve specified data rows and columns from the database. Below is a simple SELECT statement.

SELECT column_1, column_2, column_3 FROM table_name;

This statement will return the result set of selecting columns "column_1", "column_2" and "column_3" from the "table_name" table. If you want to return all columns in the table, you can use the wildcard "*" in the SELECT statement as shown below.

SELECT * FROM table_name;

In PHP, you can use two extensions, mysqli and PDO, to interact with the database. Here we mainly introduce how to use mysqli.

After connecting to the database, you can use the mysqli_query function to execute the query statement. The following code shows how to connect to the database and execute a simple query.

<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");

// 检查连接是否成功
if (!$conn) {
    die("连接失败:" . mysqli_connect_error());
}

// 执行查询
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

// 遍历结果集并输出数据
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"] . " - 名字: " . $row["name"] . " - 年龄: " . $row["age"] . "<br>";
    }
} else {
    echo "0 结果";
}

// 关闭连接
mysqli_close($conn);
?>

In the above code, first use the mysqli_connect function to establish a connection with the database, then execute the SELECT statement and use the mysqli_query function to return the result set. Then use the mysqli_fetch_assoc function to traverse the result set and output each row of data. Finally, the database connection is closed through the mysqli_close function.

The above are the basic methods of query data operations commonly used in PHP. In actual development, other statements such as JOIN, GROUP BY, WHERE, etc. may be used for advanced queries. If you want to learn more about the interaction between PHP and database, you can view the relevant documentation or refer to other materials.

The above is the detailed content of How to write PHP query data. 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