skip to Main Content

I’ve copied the W3 schools code for performing a mysqli row count function, but when I input my variables, the returned result is always ‘1’. I have checked my SQL code by entering it directly into phpMyAdmin, which returns the correct result.

This is my code:

<?php
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT COUNT(*) FROM `Existing_Bookings`";

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);
?>

I just wondered if anyone can see any obvious reason behind this? My server is running PHP 5.6 which is why I have ensured I am using mysqli, rather than mysql for this.

2

Answers


  1. If you have any rows in the table, selecting count(*) will always return just one row (as you’ve seen). The content of the row contains the actual count you’ve queried:

    $sql="SELECT COUNT(*) FROM `Existing_Bookings`";
    
    if ($result = mysqli_query($con,$sql)) {
    
      // Return the number of rows in result set
      $row = mysqli_fetch_array($result, MYSQLI_NUM);
    
      printf("Table has %d rows.n", $row[0]);
    
      // Free result set
      mysqli_free_result($result);
    }
    
    mysqli_close($con);
    
    Login or Signup to reply.
  2. Your query is counting the number of Bookings which will always return 1 row that includes the count. mysqli_num_rows will provide you with a row count so in this case it will always be 1.

    Quick Fix: change sql to SELECT * FROM Existing_Bookings

    Better Fix: check the check to read the row: $row = mysqli_fetch_row($result) and then $row[0] will contain the count.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search