6

次のクエリがあるとします。

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

このクエリは、テーブルからユーザーの数を返します。この値を PHP 変数に渡す必要があります。私はこれを使用しています:

$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;
}

必要と思われるコードを修正してください。

これが最善のアプローチです。これをどのように行うことをお勧めしますか?

4

2 に答える 2

25

このような:

// 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'];
于 2009-04-28T11:08:16.257 に答える
4

また、mysqliを使用する別の方法。これは、とにかくパラメーターの補間に使用する必要があります。

$statement = $connection->prepare($the_query_from_above);
$statement->execute();
$statement->bind_result($nr_of_users);
$statement->fetch();
于 2009-04-28T11:26:46.743 に答える