2013-02-01 79 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