B.Mayssa
B.Mayssa

Reputation: 94

How to display number of rows in a sql table using php?

I'm trying to get lines' number from the result of the sql query, so I started by connecting to the database, then checking if the connection was established and finally I tried to count the number of lines, here's the code :

 <?php   
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "db_test";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
        $res = $conn->query('SELECT COUNT (id_offre) AS nb FROM offres');
        
        $data = $res->fetch();
        
        $nb = $data['nb'];
        
        echo $nb;
?>

I get these errors :

Uncaught Error: Call to a member function fetch() on boolean

Call to a member function fetch() on boolean

I used echo to check the 'nb' value, what is the problem?

Upvotes: 1

Views: 98

Answers (2)

7060965
7060965

Reputation: 69

<?php   
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "db_test";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    // Check connection
    if (! $conn) {
       die("Connection failed: " . mysqli_connect_error());
    }

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: ".$conn - > connect_error);
    }
    $res = $conn->query('SELECT * FROM offres');
    $data_count = mysqli_num_rows($res);
    echo($data_count);

?> 

check this out!

Upvotes: -1

M. Eriksson
M. Eriksson

Reputation: 13635

Your query fails which makes $conn->query() to return false.

So, why does the query fail?

SQL doesn't allow for any spaces between function names and the parentheses, like you have at COUNT ().

So if you change:

SELECT COUNT (id_offre) AS nb FROM offres

to

SELECT COUNT(id_offre) AS nb FROM offres

...it should work.

Note: I would highly recommend you to have a read about mysqli::error() and add some error handling to your code.

Upvotes: 2

Related Questions