简体   繁体   中英

Addition in php from more than one row in mysql

Hello I am trying to make a little game, where I need to add some point given for how a drink looks and taste.

There will be 7 people giving points, so in php i need to create a table for each date and only show 1 name for each of the players, but I need the points to be added for every row with the same name:

Here is what I have so far.

  <?php     

    $pdo = Logbase::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
    $sql = 'SELECT DISTINCT start FROM grade';      
    $q = $pdo->query($sql);
    $q->setFetchMode(PDO::FETCH_ASSOC);?> 
<?php while ($r = $q->fetch()): ?>
 <table class="blueTable" align="center">

<thead>

<tr>
<th> <?php echo $r['start'] ?></th>
<th></th>
</tr>
</thead>
<?php endwhile; ?> 
<tbody>
<?php     

    $pdo = Logbase::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
    $sql = 'SELECT * FROM grade group by start, name';      
    $q = $pdo->query($sql);
    $q->setFetchMode(PDO::FETCH_ASSOC);

  ?> 
 <?php while ($r = $q->fetch()): ?>                 
<tr>
<td> <?php echo $r['name'] ?></td>
<td> <?php echo $r['drinks_fla'] + $r['drinks_view']  + $r['food'] + 
 $r['sam'] ?></td>
</tr>
<?php endwhile; ?> 
</tbody>
</table>

In my result I can see 1 name for each player, but only 1 rows has been added (the first), so I quess I need a loop or something in my mysql?

Dennis --------10 point
Michael--------6 point

I want to see Dennis 24 point Michale 12 points

id---start--- name-----drinks_fla---drinks_view

1---31.07-2017---dennis---5---5
1---31.07-2017---dennis---4---3
1---31.07-2017---dennis---5---2
2---31.07-2017---Michale---5---1
2---31.07-2017---Michael---2---4

$sql = 'SELECT * FROM grade group by start, name'; 

You have grouped your Results from MySQL, so only one Row will be called for the Properties of the Group.

Try "sum()" to get sum of the selected Columns you want:

$sql = 'SELECT name as name,sum(sum(drinks_fla),sum(drinks_view)) as sum FROM grade group by start, name';

MySQL will call all Rows, ordered by the first Property. All Rows with the same first Property are sorted with the second one.

Example:

id---start--- name-----drinks_fla---drinks_view

1---31.07-2017---dennis---5---5
1---31.07-2017---dennis---4---3
1---31.07-2017---dennis---5---2
2---31.07-2017---Michale---5---1
2---31.07-2017---Michael---2---4

Result:
name----sum
dennis----24
Michale----6
Michael----6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM