使用PHP获取排序查询的第一行和第二行中的值之间的差异

时间:2015-04-04 16:15:52

标签: php html mysql

对不起这么长的头衔感到抱歉。

我的数据库中有当前表: Table

然后我使用以下PHP代码在我的网站上显示信息:

<?php

function time_elapsed_string($datetime, $full = true) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    $string = array('y' => 'year','m' => 'month','w' => 'week','d' => 'day','h' => 'hour','i' => 'minute','s' => 'second',);
    foreach ($string as $k => &$v) {if ($diff->$k) {$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');} else {unset($string[$k]);}}
    if (!$full) $string = array_slice($string, 0, 1);
	return $string ? implode(', ', $string) . ' ago' : 'just now';
}

$servername = "localhost";
$username = "root";
$password = "";

$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,"ai-database");
// if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}

$sql = "SELECT * FROM `steam` ORDER BY `id` DESC LIMIT 1";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($query)){
	$cards = $row['cards'];
	$backgrounds = $row['backgrounds'];
	$emoticons = $row['emoticons'];
	$gifts = $row['gifts'];
	$timestamp = $row['timestamp'];
}

echo "
    <div class='category'>
      <h2>Steam Collection</h2>
      <p class='info'>
        Last Updated: <span>" . time_elapsed_string("@" . $timestamp) . "</span>
      </p>
      <div class='item'>
        <div class='title'>Cards</div>
        <div class='stat'>" . number_format($cards) . "</div>
      </div>
      <div class='item'>
        <div class='title'>Backgrounds</div>
        <div class='stat'>" . number_format($backgrounds) . "</div>
      </div>
      <div class='item'>
        <div class='title'>Emoticons</div>
        <div class='stat'>" . number_format($emoticons) . "</div>
      </div>
      <div class='item'>
        <div class='title'>Gifts</div>
        <div class='stat'>" . number_format($gifts) . "</div>
      </div>
    </div>
	";

?>

经过一段时间的CSS后,我得到了一些像这样的东西:

Display

我希望在按ID(Desc)排序后收集第一行和第二行,找出两个值之间的差异并将其显示在网站上。
我希望结果看起来像这样:

My hopes and dreams

我尝试使用以下内容,但我觉得它看起来相当混乱,也可能是不好的做法。

<?php

$sql = "SELECT * FROM `steam` ORDER BY `id` DESC LIMIT 2";
$query = mysqli_query($conn, $sql);
$i = 0;
while($row = mysqli_fetch_assoc($query)){
	if($i==0){
		$cards = $row['cards'];
		$backgrounds = $row['backgrounds'];
		$emoticons = $row['emoticons'];
		$gifts = $row['gifts'];
		$timestamp = $row['timestamp'];
		$i+=1;
	} else {
		$cards2 = $row['cards'];
		$backgrounds2 = $row['backgrounds'];
		$emoticons2 = $row['emoticons'];
		$gifts2 = $row['gifts'];
		$timestamp2 = $row['timestamp'];
	}
}

?>

有更清洁,更有效的方法吗?

2 个答案:

答案 0 :(得分:1)

在我看来你有一个非常干净的版本。您可以通过为记录引入一个对象而不是像现在这样拥有许多参数来使它变得更好。

当前版本可能如下所示:

<?php

$sql = "SELECT * FROM `steam` ORDER BY `id` DESC LIMIT 2";
$query = mysqli_query($conn, $sql);
$recordArr=array();
while($row = mysqli_fetch_assoc($query)){
    $recordObj=array();
    $recordObj['cards']=$row['cards'];
    $recordObj['backgrounds'] = $row['backgrounds'];
    $recordObj['emoticons'] = $row['emoticons'];
    $recordObj['gifts'] = $row['gifts'];
    $recordObj['timestamp'] = $row['timestamp'];
    $recordArr[]=$recordObj;
}


?>

答案 1 :(得分:1)

为什么不直接使用MySQL?

e.g。

SELECT
(
    (SELECT cards FROM steam ORDER BY id DESC LIMIT 1) 
    - (SELECT cards FROM steam ORDER BY id DESC LIMIT 1,1) 
) AS cardsDiff

编辑:您可以将逗号分隔为单个查询。然后PHP中不需要额外的变量。

编辑2:如图所示抓取相同的表/数据,见下文:

mysql> DESC steam;
+-------------+------------------+------+-----+---------------------+-----------------------------+
| Field       | Type             | Null | Key | Default             | Extra                       |
+-------------+------------------+------+-----+---------------------+-----------------------------+
| id          | int(10) unsigned | NO   | PRI | NULL                | auto_increment              |
| cards       | int(11)          | YES  |     | NULL                |                             |
| backgrounds | int(11)          | YES  |     | NULL                |                             |
| emoticons   | int(11)          | YES  |     | NULL                |                             |
| gifts       | int(11)          | YES  |     | NULL                |                             |
| timestamp   | timestamp        | NO   |     | 0000-00-00 00:00:00 | on update CURRENT_TIMESTAMP |
+-------------+------------------+------+-----+---------------------+-----------------------------+
6 rows in set (0.00 sec)

mysql> SELECT * FROM steam;
+----+-------+-------------+-----------+-------+---------------------+
| id | cards | backgrounds | emoticons | gifts | timestamp           |
+----+-------+-------------+-----------+-------+---------------------+
|  1 |   191 |         419 |       187 |    32 | 2015-04-04 16:40:42 |
|  2 |   192 |         419 |       187 |    41 | 2015-04-04 16:40:42 |
|  3 |   190 |         351 |        20 |    56 | 2015-04-04 16:40:55 |
+----+-------+-------------+-----------+-------+---------------------+
3 rows in set (0.00 sec)

mysql> SELECT
    -> (
    ->    (SELECT cards FROM steam ORDER BY id DESC LIMIT 1)
    ->     - (SELECT cards FROM steam ORDER BY id DESC LIMIT 1,1)
    -> ) AS cardsDiff,
    -> (
    ->    (SELECT backgrounds FROM steam ORDER BY id DESC LIMIT 1)
    ->     - (SELECT backgrounds FROM steam ORDER BY id DESC LIMIT 1,1)
    -> ) AS backgroundsDiff,
    -> (
    ->    (SELECT emoticons FROM steam ORDER BY id DESC LIMIT 1)
    ->     - (SELECT emoticons FROM steam ORDER BY id DESC LIMIT 1,1)
    -> ) AS emoticonsDiff,
    -> (
    ->    (SELECT gifts FROM steam ORDER BY id DESC LIMIT 1)
    ->     - (SELECT gifts FROM steam ORDER BY id DESC LIMIT 1,1)
    -> ) AS giftsDiff,
    -> (
    ->    (SELECT timestamp FROM steam ORDER BY id DESC LIMIT 1)
    ->     - (SELECT timestamp FROM steam ORDER BY id DESC LIMIT 1,1)
    -> ) AS timestampDiff;
+-----------+-----------------+---------------+-----------+---------------+
| cardsDiff | backgroundsDiff | emoticonsDiff | giftsDiff | timestampDiff |
+-----------+-----------------+---------------+-----------+---------------+
|        -2 |             -68 |          -167 |        15 |            13 |
+-----------+-----------------+---------------+-----------+---------------+
1 row in set (0.00 sec)