0

如何从我的查询 COUNT 中获取结果。

这就是我在数据库中查询的样子

   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();

?>

这是我的问题,我怎么能在 "echo "" 中传递 "Count(tbl_votes.studId)" 。 $row-> ??? . ""; " ?请帮助...

4

5 回答 5

1

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

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

于 2013-02-01T08:58:55.673 回答
0

您需要使用SQL 别名

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

然后你可以访问它$row->cnt

关于别名的一些规则:

  • 您可以在查询的其余部分使用别名(在您的示例中,您可以使用ORDER BY cnt)。注意:据我所知,您不能在另一个 select 语句中使用您在 select 中创建的别名。例如,SELECT COUNT(something) AS cnt, cnt+3 FROM......将不起作用
  • 您可以为表使用别名,并在以后的使用中将表名替换为别名
于 2013-02-01T08:59:44.843 回答
0

尝试 Select field1, field2, Count(tbl_votes.studId) as cnt from ...

于 2013-02-01T09:00:03.533 回答
0

而不是写

count(some_field)

count(some_field) as count_some_field

您为该计数字段提供别名。您可以通过 $row->count_some_field 访问它。

于 2013-02-01T09:00:53.833 回答
0

你应该使用 ' 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

有关更多信息,请参见COUNT AS

于 2013-02-01T09:02:31.350 回答