user3352340
user3352340

Reputation: 145

COUNT always returning 1

I have issue where obj->num_rows constantly returns 1 Heres my code:

$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
    echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets->num_rows . '</td></tr></table>';
$open_tickets->close();

$_SESSION['user'] is currently dextermb

Image of SQL Table

As you can see in my SQL table, there are 2 tickets with the name dextermb, so why does the code always return 1?

Upvotes: 0

Views: 377

Answers (4)

Alex Hern&#225;ndez
Alex Hern&#225;ndez

Reputation: 147

Try this:

$stm = $con->prepare("SELECT COUNT(*) as total FROM support_tickets WHERE Username = :username");
$stm->bindParam(':username', $_SESSION['user']);
$stm->execute();
$row = $res->fetch();
echo '<table><tr><th>Open Tickets</th><td>' . $row->total . '</td></tr></table>';

Note prepare and bindParam methods. This way you avoid SQL Injection.

Upvotes: 0

Mike Bovenlander
Mike Bovenlander

Reputation: 5426

The query will return the count, just use the value.

Try:

$open_tickets = $con->query("SELECT COUNT(*) FROM support_tickets WHERE Username='" . $_SESSION['user'] . "'");
echo '<table><tr><th>Open Tickets</th><td>' . $open_tickets . '</td></tr></table>';

$open_tickets->close();

Upvotes: 0

user983983
user983983

Reputation: 158

Try this

 $open_tickets = $con->query("SELECT * FROM support_tickets WHERE Username='" .                        $_SESSION['user'] . "'");
 echo '<table><tr><th>Open Tickets</th><td>' . count($open_tickets) . '</td></tr>   </table>';
  $open_tickets->close();

Upvotes: 0

Matt Healy
Matt Healy

Reputation: 18531

You are getting the number of rows returned - of course, this is only ever going to be 1. You probably want to get the value that is returned rather than the number of rows.

Upvotes: 3

Related Questions