skip to Main Content

I’m trying to count the rows which are not NULL inside a table when exucting the query inside Phpmyadmin it gives me the right output.

SELECT COUNT(`column_name`) FROM `Table_name`

but when I’m trying to execute it inside Php it always returns one I tried 2 methods both returning one for some reasons any ideas ?

method 1

$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {

        $field1name = $rowcount=mysqli_num_rows($result);


        echo '<tr> 
                  <td>English</td> 
                  <td>'.$field1name.'</td> 

              </tr>';

    $result->free();
} 

method 2

$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {
    while ($rowcount = $result->fetch_assoc()) {
        $field1name = $rowcount=mysqli_num_rows($result);


        echo '<tr> 
                  <td>Bahdini</td> 
                  <td>'.$field1name.'</td> 

              </tr>';
    }
    $result->free();
}

2

Answers


  1. The SELECT COUNT Query returns a resultset of 1 row, in that row you get the number of rows: 10228 as you stated.

    the function mysqli_num_rows returns the number of rows in the RESULTSET, that’s why it returns 1.

    Login or Signup to reply.
  2. You have several assigment in a row .. which is your expected result ??

    $field1name = $rowcount =mysqli_num_rows($result);
    

    Instaed You should use a proper column alias for your count and then query, fecth, loop over the result and show

    $query = "SELECT COUNT(`column_name`) my_count FROM `Table_name`";
    
    $result = mysqli_query($conn, $query );
    
         if (mysqli_num_rows($result) > 0) {
            while($row = mysqli_fetch_assoc($result)) {
               echo "Name: " . $row["my_count"]. "<br>";
            }
         } else {
            echo "0 results";
         }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search