2013-02-01 77 views
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(); 

?> 

我的继承人问题,我怎么能传递 “伯爵(tbl_votes.studId)” 在 “回声 ”“ $按行> ??? ”“;”?请帮助...

+0

@VladPreda感谢很多在固定的缩进题。 –

+0

没问题。我建议您使用自动执行此操作的IDE。我只是在那里复制它,并将其复制回来:) –

+0

to all ..thunk回应... –

回答

1

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

而在PHP中,你可以使用$row->stu_count

+0

@pktangyue .. thnks for respond .. –

0

您需要使用SQL alias

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 ......将无法正常工作
  • 您可以使用别名表,并在未来的别名替换表名用法
+0

..thnks for responding –

0

尝试 选择场,场2,伯爵(tbl_votes.studId )从CNT ...

0

,而不需要编写

count(some_field) 

count(some_field) as count_some_field 

您给该计数字段的别名。你可以通过$ row-> count_some_field来访问它。

0

您应该使用'作为'与'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