在新的虚拟主机上获取此错误未定义的偏移量:1和2

时间:2018-10-05 15:11:10

标签: php mysql offset

我最近将脚本移到了新的虚拟主机中,现在出现此错误

注意:未定义的偏移量:1($ id2行) 注意:未定义的偏移量:2($ id3行)

这是我的PHP代码

<?php
include '../connect_database.php'; 

$sql = "SELECT score FROM dailyscore Where Id IN (1,2,3)";
date_default_timezone_set('America/New_York');
$result = $connect->query($sql);
while ($row = mysqli_fetch_assoc($result)){
$rows[] = $row; 
$id1= $rows[0]['score'];
$id2= $rows[1]['score'];
$id3= $rows[2]['score'];

}

$list['scores'] = array('data' => $id1, 'data1' => $id2, 'data2' => $id3);

$myJSON = json_encode($list);

echo $myJSON;
print_r($rows);
?>

知道为什么吗?

1 个答案:

答案 0 :(得分:2)

我认为这是设计有缺陷的征兆。您似乎正在寻找3位玩家的得分。您正在遍历3行,但尝试在每次迭代中访问所有3个播放器的数据。您应该改为在每个玩家的各自迭代中访问它们的数据,并建立一个玩家数据列表。

要直接回答您的问题,在迭代1中,您尝试访问元素0、1和2,但是$rows仅填充了0。

+-----------+-------------------------+--------------------------+
| Iteration | You're trying to access | You only have access to  |
+-----------+-------------------------+--------------------------+
|         1 |                   0,1,2 |                        0 |
|         2 |                   0,1,2 |                      0,1 |
|         3 |                   0,1,2 |                    0,1,2 |
+-----------+-------------------------+--------------------------+

示例

<?php
// Turn on error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Show MySQL errors as PHP exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include '../connect_database.php'; 

// Build up this list inside the loop. 
$scores = [];

$sql = "SELECT score FROM dailyscore Where Id IN (1,2,3)";
date_default_timezone_set('America/New_York');
$result = $connect->query($sql);
while ($row = mysqli_fetch_assoc($result)){
    // You only have access to a single $row here. 
    // Build up an array of the data you want instead of tring to access "other rows"
    $scores[] = $row['score'];
}

// Now, you can use $scores to build $list... or build $list inside the loop. 
?>

编辑

  

您介意向我展示示例如何将数组结果分配给   这样的东西? $ list ['scores'] = array('data'=> $ id1,'data1'   => $ id2,'data2'=> $ id3);

<?php
// Turn on error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Show MySQL errors as PHP exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include '../connect_database.php'; 

// Build up this list inside the loop. 
$scores = [];
$counter = 0;

$sql = "SELECT score FROM dailyscore Where Id IN (1,2,3)";
date_default_timezone_set('America/New_York');
$result = $connect->query($sql);
while ($row = mysqli_fetch_assoc($result)){

    $keyName = 'data';

    if ($counter > 0) {
        $keyName = 'data' . $counter;
    }

    $scores[$keyName] = $row['score'];

    $counter++;
}

$list['scores'] = $scores;

echo json_encode($list);