简体   繁体   中英

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.

I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.

<?php
    $host = 'localhost';
    $user = 'MyUsername';
    $pass = 'MyPassword';
    $database = 'MyDatabase';


    $con=mysqli_connect($host,$user,$pass ,$database);
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
    $num_rows = mysql_num_rows($result);
    echo "$num_rows Rows\n"; 

    mysqli_close($con);

      ?> 

All it returns is the text Rows on the screen, without the number of rows at the start.

Like I said, this same query works and returns a value if I try and select a row using:

while($row = mysqli_fetch_array($result))
   {
    echo $row["test"];
   }

Anyone know why it won't return the number of rows?

You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value. You have to replace your mysql function with mysqli equal:

$num_rows = mysqli_num_rows($result);

You are using Mysqli to you should use mysqli_num_rows

$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'"); $num_rows = mysqli_num_rows($result);

If you want only count then you can directly use count(*) like this:-

$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");

echo $result;

I'll do some thing like this:

$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM