【问题标题】:PHP/mySQL count($array[id]) = 1 even though there are 8 elemnts in the tablePHP/mySQL count($array[id]) = 1 即使表中有 8 个元素
【发布时间】:2015-12-25 22:14:24
【问题描述】:

这是我的代码:

$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 表中有 8 个“元素”。但是当我计算数组时,它返回一个。我做错了什么?

【问题讨论】:

  • 每条记录是一个关联数组..
  • 您只计算数组中的一个字段。
  • 非常感谢大家,尤其是 Rocket 的正确命令:D

标签: php mysql sql select count


【解决方案1】:

mysqli_fetch_array 获取 单行 作为数组,其中每个元素都是一列。您可以使用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];

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多