简体   繁体   中英

Issues grabbing information from SQL database and display using PHP

I have a MySQL database that I have set up that tracks all sessions of my program run time with various variables being tracked.

I'm not that great at SQL and I wanted to see if it was possible to grab all the data from 1 specific user along with the variable data I want and add it all together.

The structure of the database looks something like this

id - username - data1- data2- data3- timestamp
0 - name1 - 0- 0- 0-10/10/2010
0 - name2 - 0- 0- 0-10/10/2010
0 - name3 - 0- 0- 0-10/10/2010
0 - name1 - 0- 0- 0-10/10/2010
0 - name1 - 0- 0- 0-10/10/2010
0 - name3 - 0- 0- 0-10/10/2010

That is just an example, I want to display the information in a PHP table, with totals of the data per user, doing it how I currently have it set up, it will create a row in the table for every single session by the user instead of adding it all up. This is my SQL call

$sql = 'SELECT * 
        FROM database
        ORDER BY data1 DESC';

and my php code is

<?php
$no     = 1;
$runtime = 0;
$profit = 0;
$deaths = 0;
while ($row = mysqli_fetch_array($query))
{
    $amount  = $row['profit'] == 0 ? '' : number_format($row['profit']);
    echo '<tr>
            <td>'.$no.'</td>
            <td>'.$row['username'].'</td>
            <td>'.convert_seconds($row['runtime']).'</td>
            <td>'.number_format($row['profit']).'</td>
            <td>'.$row['deaths'].'</td>
        </tr>';
    $runtime += $row['runtime'];
    $profit += $row['profit'];
    $deaths += $row['deaths'];
    $no++;
}?>

I know some of the variables are not matching, this is just an example of what my code is. How can I get it to grab the data from my database and add up all the sessions per username and display that?

You need to use a « GROUP BY » clause and then SUM the relevant columns.

Like :

SELECT username, SUM(data1), SUM(data2), SUM(data3)
FROM database
GROUP BY username

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