3

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • @Mureinik - accidentally caught the submit button! Just edited to finish the question off – Callum Corrigan Jan 04 '20 at 15:51
  • Does this answer your question? [How to get count of rows in MySQL table using PHP?](https://stackoverflow.com/questions/58227521/how-to-get-count-of-rows-in-mysql-table-using-php) – Dharman Jan 04 '20 at 17:59

2 Answers2

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);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
-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.

JiN264
  • 16