dongweng9474 2016-05-06 16:43
浏览 31
已采纳

Php / Mysql计数舞者从每个时刻添加问题

I have a dance contest site and each user can login and add dance moments, in my html table with all moments from all users i have all the data but i want in a html column to add "number of dancers for each moment added by the logged user id".

I have this:

$c = mysql_query("SELECT * FROM moments");
$dancers = 0;
while($rows = mysql_fetch_array($c)){
    for($i = 1; $i <= 24; $i++){
        $dan_id = 'dancer'.$i;
        if($rows[$dan_id] != "" || $rows[$dan_id] != null )
            $dancers++;
    }   
}
echo "<th class="tg-amwm">NR of dancers</th>";
echo "<td class='tg-yw4l'>$dancers</td>";

phpMyAdmin moments table: has id, clubname, category, discipline, section, and this: enter image description here

But this process is count all the dancers names from all users moments. Example for this process: You have a total of 200 dancers !

I want the process to count for me all dancers names for each moment added in the form not a total of all entire users moments, something like this: if user john has two moments added: Moment 1: 5 dancers - moment 2: 10 dancers, and so on for each user.

  • 写回答

1条回答 默认 最新

  • dongnei3634 2016-05-06 21:27
    关注

    Let me try to put you in the right way (it seems a long post but I think it's worth the beginners to read it!).

    You have been told in the comments to normalize your database, and if I were you and if you want your project to work well for a long time... I'd do it.

    There are many MySQL normalization tutorials, and you can google it your self if you are interested... I'm just going to help you with your particular example and I'm sure you will understand it.

    Basically, you have to create different tables to store "different concepts", and then join it when you query the database.

    In this case, I would create these tables:

    database diagram

    categories, dance_clubs, users and dancers store "basic" data.

    moments and moment_dancers store foreign keys to create relations between the data.

    Let's see the content to understand it better.

    mysql> select * from categories;
    +----+---------------+
    | id | name          |
    +----+---------------+
    |  1 | Hip-hop/dance |
    +----+---------------+
    
    mysql> select * from dance_clubs;
    +----+---------------+
    | id | name          |
    +----+---------------+
    |  1 | dance academy |
    +----+---------------+
    
    mysql> select * from users;
    +----+-------+
    | id | name  |
    +----+-------+
    |  1 | alex  |
    +----+-------+
    
    mysql> select * from dancers;
    +----+-------+
    | id | name  |
    +----+-------+
    |  1 | alex  |
    |  2 | dan   |
    |  3 | mihai |
    +----+-------+
    
    mysql> select * from moments;
    +----+--------------+---------------+-------------------+
    | id | main_user_id | dance_club_id | dance_category_id |
    +----+--------------+---------------+-------------------+
    |  1 |            1 |             1 |                 1 |
    +----+--------------+---------------+-------------------+
              (user alex)  (dance acad..)     (Hip-hop/dance)
    
    mysql> select * from moment_dancers;
    +----+-----------+-----------+
    | id | moment_id | dancer_id |
    +----+-----------+-----------+
    |  1 |         1 |         1 | (moment 1, dancer alex)
    |  2 |         1 |         2 | (moment 1, dancer dan)
    |  3 |         1 |         3 | (moment 1, dancer mihai)
    +----+-----------+-----------+
    

    Ok! Now we want to make some queries from PHP.

    We will use prepared statements instead of mysql_* queries as they said in the comments aswell.

    The concept of prepared statement can be a bit hard to understand at first. Just read closely the code and look for some tutorials again ;)

    Easy example to list the dancers (just to understand it):

    // Your connection settings
    $connData = ["localhost", "user", "pass", "dancers"];
    
    $conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
    $conn->set_charset("utf8");
    
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // Here we explain MySQL which will be the query
    $stmt = $conn->prepare("select * from dancers");
    // Here we explain PHP which variables will store the values of the two columns (row by row)
    $stmt->bind_result($dancerId, $dancerName);
    
    // Here we execute the query and store the result
    $stmt->execute();
    $stmt->store_result();
    
    // Here we store the results of each row in our two PHP variables 
    while($stmt->fetch()){
        // Now we can do whatever we want (store in array, echo, etc)
        echo "<p>$dancerId - $dancerName</p>";
    }
    
    $stmt->close();
    $conn->close();
    

    Result in the browser:

    dancers list

    Good! Now something a bit harder! List the moments:

    // Your connection settings
    $connData = ["localhost", "user", "pass", "dancers"];
    $conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
    $conn->set_charset("utf8");
    
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // Query to read the "moments", but we have their main user and dancers in other tables
    $stmtMoments = $conn->prepare("
        select
            moments.id,
            (select name from users where users.id = moments.main_user_id) as main_user,
            (select name from dance_clubs where dance_clubs.id = moments.dance_club_id) as dance_club,
            (select name from categories where categories.id = moments.dance_category_id) as dance_category,
            (select count(*) from moment_dancers where moment_dancers.moment_id = moments.id) as number_of_dancers
        from moments
        ");
    // Five columns, five variables... you know ;)
    $stmtMoments->bind_result($momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers);
    
    // Query to read the dancers of the "moment" with id $momentId
    $stmtDancers = $conn->prepare("
        select
            dancers.name as dancer_name
        from
            dancers join moment_dancers on dancers.id = moment_dancers.dancer_id
        where
            moment_dancers.moment_id = ?
        ");
    
    $stmtDancers->bind_param("i", $momentId);
    $stmtDancers->bind_result($momentDancerName);
    
    // Executing the "moments" query
    $stmtMoments->execute();
    $stmtMoments->store_result();
    
    // We will enter once to the while because we have only one "moment" right now
    while($stmtMoments->fetch()){
    
        // Do whatever you want with $momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers
        // For example:
    
        echo "<h3>Moment $momentId</h3>";
        echo "<p>Main user: $momentMainUser</p>";
        echo "<p>Dance club: $momentDanceClub</p>";
        echo "<p>Category: $momentDanceCategory</p>";
        echo "<p>Number of dancers: $momentNumberOfDancers</p>";
        echo "<p><strong>Dancers</strong>: ";
    
        // Now, for this moment, we look for its dancers
        $stmtDancers->execute();
        $stmtDancers->store_result();
        while($stmtDancers->fetch()){
    
            // Do whatever you want with each $momentDancerName
            // For example, echo it:
    
            echo $momentDancerName . " ";
        }
    
        echo "</p>";
        echo "<hr>";
    }
    
    $stmtUsers->close();
    $stmtMoments->close();
    
    $conn->close();
    

    Result in browser:

    moments list

    And that's all! Please ask me if you have any question!

    (I could post the DDL code to create the database of the example with the content data if you want)

    Edited: added dancers table. Renamed moment_users to moment_dancers. Changed functionality to adapt the script to new tables and names.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么