如何获取计数值


how to get the counted value

如何从查询计数中获取结果。

这就是我的查询在我的数据库中的外观

   fname  lname   mname    positionName  COUNT(tbl_votes.studId)
    jr    gwapo   is-very    chairman           2

这就是我的网页的样子

       Name           Position      Number of Votes
  jr is-very gwapo    chairman         ______

这是我的代码。

<?php
  if ($result = $mysqli->query("SELECT tbl_student.fname, tbl_student.lname, tbl_student.mname, tbl_position.positionName, Count(tbl_votes.studId) FROM tbl_candidate Inner Join tbl_student ON tbl_candidate.studId = tbl_student.studId Inner Join tbl_position ON tbl_candidate.positionId = tbl_position.positionId Inner Join tbl_votes ON tbl_student.studId = tbl_votes.candId WHERE tbl_position.positionId =  '1' GROUP BY tbl_student.fname, tbl_student.lname, tbl_student.mname, tbl_position.positionName")) {
      if ($result->num_rows > 0) {
          echo "<table border='1' cellpadding='10'>";
          // set table headers
          echo "<tr><th>Name</th><th>Position</th><th>Number of Votes</th></tr>";
          while ($row = $result->fetch_object()) {
              echo "<tr>";
              echo "<td>" . $row->fname . " " . $row->mname . " " . $row->lname . " </td>";
              echo "<td>" . $row->positionName . "</td>";
              //this is where i suppose to echo the count result
            echo "<td>" . $row-> ??? . "</td>"; 
            echo"<tr>";
          }
          echo "</table>";
      } else {
          echo "No results to display!";
      }
  }
  $mysqli->close();
?>

这是我的问题,我怎么能传递"Count(tbl_votes.studId)"回声" .$row-> ???.'"'"; '" ?请帮忙...

在 sql 查询中,将Count(tbl_votes.studId)更改为 Count(tbl_votes.studId) as stu_count

在 php 中,您可以使用$row->stu_count

您需要使用 SQL 别名

Count(tbl_votes.studId) as cnt
//or
Count(tbl_votes.studId) 'cnt'

然后,您可以使用$row->cnt访问它

关于别名的一些规则:

  • 您可以在查询的其余部分使用别名(在您的示例中,您可以使用 ORDER BY cnt )。注意:据我所知,您不能在另一个选择语句中使用您在选择中创建的别名。例如,SELECT COUNT(something) AS cnt, cnt+3 FROM...将不起作用
  • 您可以对表使用别名,并在将来的使用中将表名替换为别名

尝试 选择字段 1、字段 2、计数(tbl_votes.studId) 作为 cnt 从 ...

而不是写

count(some_field)

count(some_field) as count_some_field

您为该计数字段指定别名。您可以$row>count_some_field访问它。

你应该使用"as"和"count"。所以你的查询会变成这样

"SELECT tbl_student.fname, tbl_student.lname, tbl_student.mname, tbl_position.positionName, Count(tbl_votes.studId) as no_of_votes FROM tbl_candidate Inner Join tbl_student ON tbl_candidate.studId = tbl_student.studId Inner Join tbl_position ON tbl_candidate.positionId = tbl_position.positionId Inner Join tbl_votes ON tbl_student.studId = tbl_votes.candId WHERE tbl_position.positionId =  '1' GROUP BY tbl_student.fname, tbl_student.lname, tbl_student.mname, tbl_position.positionName"

然后你可以通过PHP获取它作为

$row->no_of_vote

有关 MOR 信息,请参阅计数为