-8

It's a simple question, but no websites or resources out there seem to tell me the answer.

I have an sql query like below:

SELECT COUNT(id) FROM Events

Simple enough! How do I get the value? How do I go about running this query in PHP so I can print the result?

(By the way, I know how to print something row-by-row in a select statement, but all I need here is one value, and all online tutorials stop at this point and don't give me the PHP code. I've been looking for days! It's like I know how to drive - I just need someone to tell me where to find the car keys.)

=======

I'll explain my question more. A lot of people are pointing me to other pages (which I've seen) that don't actually explain HOW to get the data.

Here's my code so far:

    $sql8 = "SELECT COUNT(ID) as counter FROM Events";
        $result8 = $conn->query($sql8);
        if ($result8->num_rows > 0) {
            while($row8 = $result8->fetch_assoc()) {
            echo $row8['counter'].".".$row8['COUNT(ID)'];
            }
        }

This WORKS, but I don't think this is the most efficient way to write it. How do I execute this query? That's the main part of my question. How I get the count from it works (thanks) but now it's a matter of writing it properly.

Thanks, Brendan

Brendan
  • 107
  • 2
  • 13
  • https://www.w3schools.com/php/func_mysqli_query.asp – dwib Oct 25 '19 at 02:07
  • https://www.php.net/manual/pdostatement.fetchcolumn.php#72609 – Phil Oct 25 '19 at 02:23
  • 1
    What extension/lib are you using to write your queries? – Jarzon Oct 25 '19 at 02:23
  • Possible duplicate of [select count(\*) from table of mysql in php](https://stackoverflow.com/questions/6907751/select-count-from-table-of-mysql-in-php) – catcon Oct 25 '19 at 03:16
  • I read all these links. None really explain the full answer. They all have parts of the code, which I can find anywhere, but not COMPLETE solution. – Brendan Oct 25 '19 at 14:23
  • Sound like a [X-Y Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you explain what are you trying to do? Why do you think your code is not the most efficient way to write? – catcon Oct 25 '19 at 22:19

1 Answers1

1

If you already know how to print select statement data, you should do the same for this query. I think you have problems to map the column:

while($row=$result->fetch_assoc){
  $data=$row['COUNT(id)'];
}

// or you can use SELECT COUNT(id) as counter FROM Products;

Then you can map the column: $row['counter'];
Xhuljo
  • 689
  • 6
  • 12