MySQL - count total number of rows in php
What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows
is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use COUNT
in a SELECT
query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);