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()); }
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'];
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);
3. Complete code example
The following is a complete PHP query MySQL database Quantity sample code:
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!