1

I want to know the total products in my product table but it shows an error. What will be the right syntax?

here is my code:

$sql = "SELECT COUNT(product_name) FROM product";
$result=mysqli_query($this->conn,$sql);
$row = $result->fetch_object();
$neeraj =  $row->COUNT(product_name);
echo $neeraj;
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 3
    Please [edit] your question and include the complete error message. – Dave Dec 30 '19 at 21:44
  • rename the count in the sql to a name, otherwise "count(product_name)" will be interpreted as a function call, so in the sql use "count(...) AS NAME" and then in PHP use "->NAME" – Alberto Sinigaglia Dec 30 '19 at 21:50
  • @AlbertoSinigaglia Comment section is not meant for answers. If you have a solution please use the Answer space. Comments will be removed. – Dharman Dec 30 '19 at 22:22
  • @Dharman i'm not sure about my answer, because i've not tested it... if turns out to be right, i will create the answer and let the creator mark that as supposed correct answer – Alberto Sinigaglia Dec 30 '19 at 23:48
  • @AlbertoSinigaglia This was more of a suggestion for future, because this question has already been answered and is closed as duplicate. In future either flag to close or answer. You can delete an answer if it turns out to be wrong. – Dharman Dec 30 '19 at 23:50

1 Answers1

2

If I remember correctly, to get the count you should submit COUNT(…) query and get the first column of the result.
So, correct code would be look like this:

$sql = "SELECT COUNT(product_name) FROM product";
$result = $this->conn->query($sql);
$neeraj = (int) $result->fetch_row()[0];
echo $neeraj;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Celestine
  • 25
  • 3