while循环从mysql表中重复数组的最后一行

时间:2018-12-15 22:18:23

标签: php mysql

我想从与查询匹配的mysql表中获取所有行 截至目前,我有两行与匹配的查询,我将每一行保存在 $tourData变量,然后在while循环中将其添加到$allTourData变量中。

此函数在我的$allTourData中返回两个数组,但我却两次获得了第一行和第二行。

这是我的代码。

public static function getTourAvailabilityStatus($date, $route)
{
    $lt   = MySQL::connect();
    $tour = $lt->prepare
    (   /** @lang MySQL */
        "
            SELECT id, token, route, date, travels_name, bus_number, st, aj, wt, sl
            FROM tour
            WHERE date = ? AND route = ? ;
            "
        );

    MySQL::error($tour, $lt);
    $tour->bind_param('ss', $date, $route);
    MySQL::error($tour, $lt);
    $tour->execute();
    MySQL::error($tour, $lt);
    $tourData = [];
    $tour->bind_result(
        $tourData['id'], $tourData['token'], $tourData['route'], $tourData['date'], $tourData['travelsName'],
        $tourData['BusNumber'], $tourData['st'], $tourData['aj'], $tourData['wt'], $tourData['sl']
    );
    MySQL::error($tour, $lt);
    $allTourData = [];
    while($tour->fetch())
    {
        $allTourData[] = $tourData;
    }
    MySQL::error($tour, $lt);
    $tour->close();

    return $allTourData;
}

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

public static function getTourAvailabilityStatus($date, $route)
{
    $lt   = MySQL::connect();
    $tour = $lt->prepare
    (   /** @lang MySQL */
        "
            SELECT id, token, route, date, travels_name, bus_number, st, aj, wt, sl
            FROM tour
            WHERE date = ? AND route = ? ;
            "
        );

    MySQL::error($tour, $lt);
    $tour->bind_param('ss', $date, $route);
    MySQL::error($tour, $lt);
    $tour->execute();
    MySQL::error($tour, $lt);

    $tour->bind_result(
        $id, $token, $route, $date, $travelsName,$BusNumber, $st, $aj, $wt, $sl
    );
    MySQL::error($tour, $lt);
    $allTourData = [];
    while($tour->fetch())
    {
        $allTourData[] = [ $id, $token, $route, $date, $travelsName,$BusNumber, $st, $aj, $wt, $sl];
    }
    MySQL::error($tour, $lt);
    $tour->close();

    return $allTourData;
}