-2

Given the code:

$counters = $db->query("SELECT COUNT(film_id) FROM review WHERE film_id = $film_id ");

I need to convert the object $counters into an integer. FYI: the query returns a single int i.e 4 (depending on the film_ID)

hotkeying
  • 1
  • 2

2 Answers2

0

Give an alias to the column that stores the COUNT result then use it as you would use with any other SELECT query.

$counters = $db->query("SELECT COUNT(film_id) AS counter FROM review WHERE film_id = $film_id ");
$counter = $counters->fetch_assoc();

echo $counter['counter'];
Ibrahim
  • 2,034
  • 15
  • 22
  • I need the value stored in a single variable to be used as a counter in some kind of loop later on. I plan on using the counter to iterate over a series of echos. The number of iterations must depend on the counter - so you see why it must be stored in a single variable? Thanks – hotkeying Dec 27 '15 at 00:27
  • I don't really understand, you have the $counter['counter'] variable that you can use later. If you really want on a single line, then you can do something like this: `$counters = $db->query("SELECT COUNT(film_id) AS counter FROM review WHERE film_id = $film_id")->fetch_assoc()['counter'];` – Ibrahim Dec 27 '15 at 00:35
0

$counters is not the result string you assume, but a resource object.

My suggestion is to change the code as follows:

$res = $db->query("SELECT COUNT(film_id) as counter FROM review WHERE film_id = $film_id ");
$row = $res->fetch_assoc();
$counter = (int) $row["counter"];
S. Alcic
  • 81
  • 4