0

When I do a SQL search in phpMyAdmin (substituting the variable for the actual value) it returns the correct row number but when using PHP to return this value it always returns 1 no matter what. Thanks in advance.

function user_exists($username) { $link = mysqli_connect('localhost','root','','test'); $username = sanitize($username); $query = mysqli_query($link, "SELECT COUNT(`user_id`) FROM `new_base` WHERE `username`='$username'"); $row_cnt = mysqli_num_rows($query); echo $row_cnt; mysqli_free_result($query); mysqli_close($link); } 
3
  • your reading how many rows the SELECT returned not the row number Commented Aug 5, 2013 at 18:40
  • It has been asked zillion times already... Commented Aug 5, 2013 at 18:40
  • 1
    COUNT is a group function. It combines the rows into one result. What exactly do you want this query to return? You probably need a GROUP BY in there. Commented Aug 5, 2013 at 18:42

2 Answers 2

6

When you use COUNT(*) you always get one row returned even if the count is zero.

You either:

  1. Want to remove the count(*) and then use mysqli_num_rows() or
  2. Get the result of count(*)

.

$row = mysqli_fetch_assoc($query); echo $row['COUNT(`user_id`)']; 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, went with your first suggestion
I fixed a slight typo there John, after Googling something for another question today. Let's see if they come your way ;-) Question being stackoverflow.com/q/39002738
@Fred-ii- Good catch!
@JohnConde :-) I've my best glasses on today.
1

Count retrives a single row. Try testing the SQL in phpmyadmin and see the result. This single row returned by the query has the number you are looking for.

I suggest also doing something like

SELECT COUNT('user_id') AS user_matches FROM .... 

This way you can access the via the 'user_matches' key.

*I would not recommend using SELECT * FROM ... * with the num_rows, this would be very slow compared to a count().

1 Comment

in this particular case it won't be very slow but actually the same. But in general you are right

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.