user4427637
user4427637

Reputation:

SQL count query returning number of rows preset as 1 instead of actual number of rows

Below is PHP code from where I'm fetching a number of rows in a database table. But following code is returning a number of rows as 1 always. Please help me solve the problem to fetch the correct number of rows from the database.

$db=mysqli_connect("localhost","root","","test");               
     echo "<div class='row text-center col-lg-12' align='center'>";     
    $cmd="SELECT COUNT(*) FROM product WHERE product_name LIKE '%$search_query%'";

    $result = mysqli_query($db, $cmd);
    $total = mysqli_num_rows($result);

Upvotes: 0

Views: 118

Answers (2)

Riaz Laskar
Riaz Laskar

Reputation: 1322

This should work:

$db=mysqli_connect("localhost","root","","test");               
     echo "<div class='row text-center col-lg-12' align='center'>";     
    $cmd="SELECT * FROM product WHERE product_name LIKE '%$search_query%'";

    $result = mysqli_query($db, $cmd);
    $total = mysqli_num_rows($result);

Upvotes: 0

rickdenhaan
rickdenhaan

Reputation: 11318

If you do a SELECT COUNT(*) you will get a row back where the counted value is in the first column. So you need to get the COUNT() value like this:

$result = mysqli_query($db, $cmd);
$row = mysqli_fetch_array($result);
$total = $row[0];

Upvotes: 2

Related Questions