PHP | MySQLiでデータの総数や検索結果のヒット数を取得する方法

PHPのMySQLiでデータの総数や検索結果のヒット数を取得するmysqli_num_rows()を利用します。
テーブル内のデータ総数を取得するサンプルコード
$sql = "select * from `テーブル名`";
$res = $mysqli->query($sql);
if (!$res) {error_log($mysqli->error);exit;}
$count = mysqli_num_rows($res);
総数の取得だけであれば取得対象を*ではなくidだけにしておくと処理は軽くなります。
$sql = "select id from `テーブル名`";
$res = $mysqli->query($sql);
if (!$res) {error_log($mysqli->error);exit;}
$count = mysqli_num_rows($res);
検索結果のヒット数を取得するサンプルコード
WHEREを使った検索結果のヒット数を取得する場合も同様に記述可能です。
$str_sql = "select * from テーブル名 WHERE `point` = '10'";
$res = $mysqli->query($str_sql);
if (!$res) {error_log($mysqli->error);exit;}
$count = mysqli_num_rows($res);
ディスカッション
コメント一覧
まだ、コメントがありません