Home > Database > Mysql Tutorial > body text

How to query the number of data in mysql in php

WBOY
Release: 2023-05-27 10:32:46
forward
1173 people have browsed it

1. Connect to MySQL database

Before using PHP to operate the MySQL database, you need to connect to the database first. You can use the mysqli_connect() function to connect. This function needs to pass in four parameters, namely the MySQL server address, MySQL user name, MySQL password and the name of the database to be connected. The following is a sample code for connecting to a MySQL database:

$conn = mysqli_connect("localhost", "root", "password", "test");
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
Copy after login

This code will try to connect to the database named test. If the connection fails, an error message will be output and the program will terminate.

2. Query the quantity of data

To query the quantity of data in the MySQL database, you can use the SELECT COUNT() FROM table name SQL statement. Among them, COUNT() represents the number of rows that meet the query conditions, and the table name is the name of the table to be queried. The following is a sample code for querying the number of data:

$sql = "SELECT COUNT(*) as count FROM users";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$count = $row['count'];
Copy after login

This code will count the total number of data in the table named users and store the result in the variable $count. After completing the query, the mysqli_free_result() function should be called to release the memory occupied by the query results

mysqli_free_result($result);
Copy after login

3. Complete code example

The following is a complete PHP query MySQL database Quantity sample code:

Copy after login

Connect to the database named "test", query the total number of data in the table named "users" and print the results. To close the database connection, you need to use the mysqli_close() function, after querying the results.

The above is the detailed content of How to query the number of data in mysql in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template