1

I am trying to get the number of rows meeting certain criteria from a database.

I have a MySQL phpMyAdmin database called ovs and in it there's a table called results with 10 columns and a sample of 5 rows so far. The column I am interested in is named chairperson. I want to get the number of rows that have Tony Montana as the chairperson. How do I accomplish this?

This code of mine does not seem to work. It doesn't even output anything.

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

$sql="SELECT COUNT(*) FROM results WHERE chairperson=Tony Montana";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  printf("%d",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }
  mysqli_close($con);
  ?>

This code does not seem to work. It doesn't even output anything. What is going on?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Stephen Muga
  • 183
  • 8
  • 2
    You need to quote the value to compare like `chairperson='Tony Montana'` – executable Apr 04 '19 at 13:27
  • 1
    It's an SQL error as Tony Montana needs quote marks around it, escaped of course. You might want to try displaying errors if you are in your development area - quickest way to spot a problem with SQL. – Watts Epherson Apr 04 '19 at 13:28
  • 1
    *"You might want to try displaying errors if you are in your development area "* @AdamWhateverson is right this is how you would do that in PHP code `ini_set('display_errors', true); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_STRICT);` – Raymond Nijland Apr 04 '19 at 13:31
  • Yeah, this just returns a 1, which is incorrect – Stephen Muga Apr 04 '19 at 13:33

1 Answers1

0

You should warp liter string value in quote

SELECT COUNT(*) FROM results WHERE chairperson='Tony Montana';


$sql="SELECT COUNT(*) FROM results WHERE chairperson='Tony Montana';";
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107