HOWTO · PHP
從 PHP 中的 MySQL 表中選擇計數函式
select count(*) 函式可以對行進行計數,並從 PHP 中的 MySQL 表中獲取查詢返回的總記錄。
本頁內容
本教程將介紹 select count(*) 函式,計算行數,並從 PHP 中的 MySQL 表中獲取查詢返回的總記錄。與教程一起工作的示例程式碼及其輸出。
第一步是用 PHP 連線到 MySQL 表資料庫。下面是我們用來連線資料庫的示例程式碼。
示例程式碼 1:
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database
$con = mysqli_connect("localhost", $user, $pass, $db);
//The code does not have an output, so we decided to print 'Database Connected'
echo "Database Connected";
?>
請記住用包含你的 MySQL 表的資料庫的名稱替換 sample tutorial。
上面的程式碼在連線成功時通常不顯示任何輸出。在我們的例子中,我們決定列印 Database Connected 作為可選輸出。
我們資料庫中的表如下:
| CarID | BrandName | OwnersName | RegistrationNumber |
|---|---|---|---|
| 1 | Benz | John | KDD125A |
| 2 | Porsche | Ann | KCK345Y |
| 3 | Buggatti | Loy | KDA145Y |
| 4 | Audi | Maggie | KCA678I |
| 5 | Filder | Joseph | KJG998U |
| 6 | Tesla | Tesla | KMH786Y |
使用 PHP 中的 Select Count(*) 函式計算 MySQL 表中的行數
下面是使用 PHP 的 select count(*) 函式計算 MySQL 表中行數的示例程式碼。
示例程式碼 2:
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database
$con = mysqli_connect("localhost", $user, $pass, $db);
$sql = "SELECT * FROM parkinglot1";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
printf("Number of rows in the table : %d\n", $num_rows);
?>
輸出:
Number of rows in the table : 6
使用 PHP 中的 Select Count(*) 函式在 MySQL 表中顯示查詢返回的總記錄
select count(*) 函式可以獲取資料庫表中查詢返回的總記錄數。
下面是一個示例程式碼,用於顯示 BrandName 類別中的總記錄。
示例程式碼 3:
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
$con = mysqli_connect("localhost", $user, $pass, $db);
$sql = "SELECT COUNT(BrandName) AS total FROM parkinglot1";
$result = mysqli_query($con, $sql);
$data = mysqli_fetch_assoc($result);
echo $data['total']
?>
輸出:
6
請記住用包含你的 MySQL 表的資料庫的名稱替換 sample tutorial。
OwnersName 類別的另一個示例程式碼和輸出。
示例程式碼 4:
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
$con = mysqli_connect("localhost", $user, $pass, $db);
$sql = "SELECT COUNT(OwnersName) AS total FROM parkinglot1";
$result = mysqli_query($con, $sql);
$data = mysqli_fetch_assoc($result);
echo $data['total']
?>
輸出:
6
我們使用 SELECT * FROM parklot1 來計算行數,並使用 SELECT COUNT(*) AS total FROM parklot1 來顯示從我們的 MySQL 表中查詢返回的總記錄。