表PHP中的计数发生回显

时间:2014-05-01 02:28:24

标签: php html mysql

我是PHP和MySQL的新手。虽然StackOverflow中有很多例子,但它们都不适用于我的情况。

所以,我有一个表(名为 votes ),如下所示:

 student_name | student_id | teacher
----------------------------------------
Joe           | 991991991  | Mr. Smith
Sally         | 717356152  | Ms. Lozano
Benny         | 383717747  | Mr. Johnson
Jim           | 191918918  | Mr. Smith
John          | 182783718  | Mr. Smith
Alfred        | 374878372  | Mr. Johnson

我想要一个HTML / PHP页面在我的一个DIV中输出,自动循环查看教师的所有选项并计算每位教师出现的次数。我希望它能够在添加新教师时自动统计新教师,这样我就不必更改后面的代码了。

Mr. Smith: 3
Mr. Johnson: 2
Ms. Lozano: 1

它不需要任何顺序,我不应该将它们从最小到最大。

我尝试过像

这样的事情
<?php SELECT teacher, SUM(1) FROM votes GROUP BY teacher ?>

SELECT teacher, count(teacher) 
  FROM votes 
 GROUP by teacher

但是他们没有工作并且给我一个错误"syntax error, unexpected 'teacher' (T_STRING)" 我可能只是错误地执行它们。他们只是自己发生,还是他们需要自己的联系或他们自己的声明或之前的事情?

有什么建议吗?

编辑:这是我的完整正文代码与我的联系...

$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
?>
</head>
    <body>
    <div align="center">
    <form method="post" action="vote_1.php">
    <h1>Counted Vote Totals</h1>
    <h4>(these values are current)</h4>
    <h2>Votes by Cantidate</h2>
    <?php SELECT teacher, count(teacher) 
  FROM votes 
 GROUP by teacher ?>
</br></br></br>
</form>
</body>

由于密码等问题,我没有把头包括在内。

1 个答案:

答案 0 :(得分:1)

这究竟是什么:

<?php SELECT teacher, count(teacher) 
  FROM votes 
 GROUP by teacher ?>

就PHP而言,这是纯文本&amp;不是MySQL查询。快速地脱离我的头脑,这应该可以向您展示PHP&amp;的基本概念。 MySQL互相合作。请注意mysql_query

$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$result = mysql_query("SELECT teacher, count(teacher) as teacher_count FROM votes GROUP by teacher;");

while ($row = mysql_fetch_assoc($result)) {
    echo $row['teacher'];
    echo $row['teacher_count'];
}

也就是说,mysql_*前缀PHP函数已被折旧。这意味着他们将不再适用于即将推出的PHP版本。以下是使用mysqli_*代替using examples from the official PHP documentation的代码版本:

$link = mysqli_connect($serverName, $userName, $password, $dbname);

// Check the connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Select queries return a resultset
if ($result = mysqli_query($link, "SELECT teacher, count(teacher) as teacher_count FROM votes GROUP by teacher;")) {
    // This is optional. Feel free to comment out this line.
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    // Cycle through results
    while ($row = $result->fetch_object()){
        echo $row['teacher'];
        echo $row['teacher_count'];
    }
}