简体   繁体   English

问题从SQL数据库获取信息并使用PHP显示

[英]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. 我有一个已建立的MySQL数据库,该数据库可跟踪程序运行时的所有会话,并跟踪各种变量。

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. 我不太擅长SQL,我想看看是否有可能从1个特定用户那里获取所有数据以及所需的变量数据,然后将它们全部加在一起。

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. 只是一个例子,我想在PHP表中显示信息,每个用户的数据总数,按照我目前的设置进行,它将在表中为用户的每个会话创建一行而不是全部添加。 This is my SQL call 这是我的SQL电话

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

and my php code is 和我的PHP代码是

<?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. 您需要使用«GROUP BY»子句,然后对相关列求和。

Like : 喜欢 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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