Procedural Approach to Counting MySQL Table Rows in PHP
Getting the count of rows in a MySQL table is a common task in PHP. To accomplish this using a procedural approach, follow these steps:
-
Establish a Database Connection: Connect to the MySQL database using mysqli_connect() and provide the host, username, password, and database name.
-
Create MySQL Query: Compose a query to retrieve the row count using SELECT COUNT(*) from the desired table. For example, $sql = "SELECT COUNT(*) FROM news";.
-
Execute Query: Use mysqli_query() to execute the query and store the result in a variable.
-
Fetch Result: Use mysqli_fetch_assoc() to retrieve the result as an associative array.
-
Get Row Count: Extract the value associated with 'COUNT(*)' from the associative array and store it in a variable.
$sql = "SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_assoc($result)['COUNT(*)'];
Copy after login
Alternative Methods:
Beyond the procedural approach:
-
Column Alias: Include a column alias in the query, such as SELECT COUNT(*) AS cnt, to simplify array fetching.
-
Numerical Array: Use mysqli_fetch_row() to retrieve the result as a numerical array and access the first element for the row count.
-
PHP 8.1: Utilize mysqli_fetch_column() to directly retrieve the first column value.
$count = mysqli_fetch_column($result);
Copy after login
Conclusion:
Using PHP's procedural methods, you can effectively count MySQL table rows. Remember to consider alternative methods for simplified code and performance optimizations.
The above is the detailed content of How to Efficiently Count MySQL Table Rows Using PHP's Procedural Approach?. For more information, please follow other related articles on the PHP Chinese website!