Count occurrence in table PHP echo

前端 未结 1 1095
孤城傲影
孤城傲影 2021-01-17 05:56

I’m new to PHP and MySQL & while there are a bunch of examples on this throughout StackOverflow, but none of them apply very well to my situation.

So, I have a t

相关标签:
1条回答
  • 2021-01-17 06:52

    What exactly is this here:

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

    As far as PHP is concerned, that is plain text & not a MySQL query. Quickly off the top of my head, this should work to show you the basic concept of how PHP & MySQL work with each other. Note the 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'];
    }
    

    That said, mysql_* prefixed PHP functions are depreciated. Meaning they will no longer work in upcoming version of PHP. So here is a version of your code using mysqli_* instead 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'];
        }
    }
    
    0 讨论(0)
提交回复
热议问题