Home >Backend Development >PHP Tutorial >How to retrieve data from database using PHP functions?

How to retrieve data from database using PHP functions?

王林
王林Original
2024-04-30 12:12:01900browse

In PHP, you can use the mysqli_query() function to retrieve database data, and use the mysqli_fetch_row(), mysqli_fetch_assoc() and mysqli_fetch_array() functions to extract results to get row data, and the mysqli_num_rows() function to get row data in the result set. quantity.

如何使用 PHP 函数从数据库中检索数据?

How to use PHP functions to retrieve data from the database

In PHP, a variety of functions are provided to operate the database and retrieve data. The following is a practical case of the commonly used function beserta:

mysqli_query() Function

Syntax:

mysqli_query(mysqli $link, string $query)

Actual case:

$link = mysqli_connect("localhost", "root", "password", "my_database");
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query);

mysqli_fetch_row() function

Syntax:

mysqli_fetch_row(mysqli_result $result)

Practical case:

while ($row = mysqli_fetch_row($result)) {
  echo $row[0] . " " . $row[1] . "\n";
}

mysqli_fetch_assoc() function

Grammar:

mysqli_fetch_assoc(mysqli_result $result)

Practical case:

while ($row = mysqli_fetch_assoc($result)) {
  echo $row['name'] . " " . $row['email'] . "\n";
}

mysqli_fetch_array() function

Grammar:

mysqli_fetch_array(mysqli_result $result)

Practical case:

while ($row = mysqli_fetch_array($result)) {
  echo $row[0] . " " . $row['name'] . "\n";
}

mysqli_num_rows() function

Syntax:

mysqli_num_rows(mysqli_result $result)

Actual case:

$num_rows = mysqli_num_rows($result);
echo "The number of rows in the result set is: " . $num_rows;

The above is the detailed content of How to retrieve data from database using PHP functions?. 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