PHP/mySQL count($array[id]) = 1 即使 table 中有 8 个元素

PHP/mySQL count($array[id]) = 1 even though there are 8 elemnts in the table

这是我的代码:

$host = "localhost";
$user = "root";
$pw = "";

$dbName = "mathgame";
$tblName = "fragen";
// mit mysql db verbinden

$con = mysqli_connect($host, $user, $pw, $dbName);
if ($con->connect_error) {
die ("Connection failed: " . $con->connect_error);}

// Datenanfrage an db

$result = mysqli_query($con, "select id from $tblName");
$array = mysqli_fetch_array($result);
echo count($array["id"]);

评论是德语的,但我想您明白程序的作用了。 所以我的问题是,fragen table 中有 8 个 "elements"。但是当我数数组时,它 returns 一个。我做错了什么?

mysqli_fetch_array fetches a single row as an array, where each element is a column. You could use mysqli_num_rows 获取当前查询的行数:

$result = mysqli_query($con, "select id from $tblName");
echo mysqli_num_rows($result);

或者,更好的是,让数据库为您完成繁重的工作:

$result = mysqli_query($con, "SELECT COUNT(*) FROM $tblName");
$array = mysqli_fetch_array($result);
echo $array[0];