简体   繁体   中英

PHP mysqli_num_rows() Function not working

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM