从MySql从获取的数组中获取精确值

时间:2016-06-10 04:56:57

标签: php mysql

不是Select specific value from a fetched array

的副本

我有一个MySql数据库: enter image description here

这是我的疑问:

$sql = "SELECT * FROM data ORDER BY Score DESC";

我希望它成为一个排行榜,人们可以更新他们的分数,因此我无法使用

$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";

我想在查询中获取第二行的用户名。所以我写道:

<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

}
echo "Result = '".$row[1]['Username']."''";
}

?>

但它会返回Result =&#39;&#39;就像数组中没有任何东西一样。

但如果我写

if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    echo "Name = '".$row['Username']."''";
}
}

它会回归:Parham,Mojtaba,Gomnam,Masoud, 那么我在第一个片段中做错了什么呢?

3 个答案:

答案 0 :(得分:1)

您无法在while循环之外访问$row

因此将结果存储在一个新数组中,然后您可以在while循环外访问该新数组:

$newResult = array();
if($result->num_rows>0){
  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
      $newResult[] = $row;
  }
}

echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array

答案 1 :(得分:1)

因为您在

之后写了ORDER之后的条件
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";

查询序列是

 SELECT * FROM data // select first
 WHERE ID = 1
 ORDER BY Score DESC// Order by at last

检查http://dev.mysql.com/doc/refman/5.7/en/select.html

对于第二种情况,您需要在循环中获取Username并使用$row['Username']代替$row[1]['Username']

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
   echo "Result = '".$row['Username']."''";// write inside while loop
}

答案 2 :(得分:0)

您可以将行值分配给任何数组并使用该数组。

<?php
    include "l_connection.php";
    $sql = "SELECT * FROM data ORDER BY Score";
    $result = mysqli_query($conn, $sql);
    if($result->num_rows>0){
        $rows = array();
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
            $rows[] = $row;
        }
        echo "Result = '".$rows[1]['Username']."'";
    }

?>

或者,如果您只想从列中获得第二高分,则可以将用户限制为

$sql = "SELECT * FROM data ORDER BY Score limit 1,1";