根据ID获取前4行最高行

时间:2015-02-05 07:07:57

标签: php mysql mysqli

我试图抓住表中最高的4行并为它们分配变量,以便我可以在整个代码中使用它们。

到目前为止,这是我能够得到的......

        <?php
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
$conn = mysqli_connect(localhost, $username, $password, $database);

$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);

    while($row = $result->fetch_assoc()) {
              $name =($row["name"]);
              $message =($row["message"]); 
              $time =($row["time"]); 
    }


?>

如何分配更多变量以获得接下来的3行?

3 个答案:

答案 0 :(得分:1)

我相信这是(对不起,漫长的一天,所以我可能会离开)

$result = array();
while(...){
      $result[] = $row;
}

答案 1 :(得分:1)

我建议你遍历结果集并将每次迭代分配给一个数组,然后你可以稍后将值拉回数组。
这是您的代码的工作更新

// ...
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);

// create array to hold queried result set
$output = array();

// loop through result set and assign each row to a key in $output array
// Note: the fetch_assoc() method auto-increments an internal pointer 
// so as you spin through the result set $row will move down the rows
while($row = $result->fetch_assoc()) {
    $output[] = $row;
}

// $output now contains an associative array on each key representing
// each row, so to access each row:
foreach($output as $row) {
    echo $row["name"] . "<br>";
    echo $row["message"] . "<br>";
    echo $row["message"] . "<hr>";
}

答案 2 :(得分:0)

之后将$result定义为数组
$result = array();
while($row= .... ){
$var= $row['name'];
.............
}