mysqli_fetch_array将数据转换为数组并存储在php变量中

时间:2015-03-26 21:22:32

标签: php mysql arrays mysqli

我正在研究这个PHP代码,我希望在每次游泳中检索每个成员的AVG时间和LAP时间。我想在检索到HTML之前先将数据存储到变量中。

在下面的代码中我没有收到任何错误。只获得笔画名称。不是AVGLaps或LapsTime

$sql = "SELECT strokeType,AVG(totalLaps),AVG(totalSeconds) FROM performance where members_memberId = '$memberid' GROUP BY strokeType";

$result=mysqli_query($con,$sql);
$performanceData = array();

while($row = mysqli_fetch_array($result)) {
  $performanceData[] =$row;
}

$stroke1 = $performanceData[0]['strokeType'];
$stroke2 = $performanceData[1]['strokeType'];
$stroke3 = $performanceData[2]['strokeType'];
$stroke4 = $performanceData[3]['strokeType'];

$strokeLaps1 = $performanceData[0]['totalLaps'];
$strokeLaps2 = $performanceData[1]['totalLaps'];
$strokeLaps3 = $performanceData[2]['totalLaps'];
$strokeLaps4 = $performanceData[3]['totalLaps'];

$strokeTime1 = $performanceData[0]['totalTime'];
$strokeTime2 = $performanceData[1]['totalTime'];
$strokeTime3 = $performanceData[2]['totalTime'];
$strokeTime4 = $performanceData[3]['totalTime'];

echo "StrokeName:".$stroke1.".";

2 个答案:

答案 0 :(得分:3)

您应该在SQL查询中声明别名:

$sql = "SELECT strokeType,AVG(totalLaps) AS avgTotalLaps,AVG(totalSeconds) AS avgTotalSeconds FROM performance where members_memberId = '$memberid' GROUP BY strokeType";

然后得到像以下的变量:

$strokeLaps1 = $performanceData[0]['avgTotalLaps'];
...

答案 1 :(得分:1)

如果要使用totalLaps和totalTime作为关联索引,则需要在SQL语句中为列添加别名。

SELECT strokeType, AVG(totalLaps) totalLaps, AVG(totalSeconds) totalTime