6

Let say that we have the following query:

SELECT DISTINCT COUNT(`users_id`) FROM `users_table`;

this query will return the number of the users from a table. I need to pass this value to a PHP variable. I'm using this:

$sql_result = mysql_query($the_query_from_above) or die(mysql_error());

if($sql_result)
{
    $nr_of_users = mysql_fetch_array($sql_result);
}
else
{
    $nr_of_users = 0;
}

please correct my code where you think is necessary.

Which is the best approach. How do you recommend to do this ?

1
  • Have you tried to do a print_r ( $sql_result ) to see what it returns? It returns an array, so you can pick up stuff through $num = $result[0][0], for example (do an if (isset(.)) first) Commented Apr 28, 2009 at 11:09

2 Answers 2

25

Like this:

// Changed the query - there's no need for DISTINCT
// and aliased the count as "num"
$data = mysql_query('SELECT COUNT(`users_id`) AS num FROM `users_table`') or die(mysql_error());

// A COUNT query will always return 1 row
// (unless it fails, in which case we die above)
// Use fetch_assoc for a nice associative array - much easier to use
$row = mysql_fetch_assoc($data);

// Get the number of uses from the array
// 'num' is what we aliased the column as above
$numUsers = $row['num'];
Sign up to request clarification or add additional context in comments.

Comments

4

Also, an alternative using mysqli, which you should be using anyway for parameter interpolation:

$statement = $connection->prepare($the_query_from_above);
$statement->execute();
$statement->bind_result($nr_of_users);
$statement->fetch();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.