SQL没有为第二行获取ID

时间:2013-02-18 14:29:43

标签: php mysql pdo

我有一个SQL查询似乎没有获取第二行的ID。我该如何解决?

               $sql = "SELECT 
                        *
                        FROM ts_request
                        INNER JOIN ts_day
                        ON ts_request.day_id = ts_day.id
                        INNER JOIN ts_period
                        ON ts_request.period_id = ts_period.id
                        INNER JOIN ts_allocation
                        ON ts_request.id = ts_allocation.request_id
                        WHERE ts_request.round=:round
                        AND ts_request.dept_id=:dept
                        ORDER BY ts_request.module_id ASC";
        }
        $stm = $pdo->prepare( $sql );
        $stm->execute( array( ':round' => 'P', ':dept' => $loggedin_id  ) );
        $rows = $stm->fetchAll();        


        foreach ($rows as $row) 
        {
        $row_id = $row['id'];
        echo '<tr align="center">'; 
        echo '<td>'.$row['module_id'].'</td>';
        echo '<td>'.$row['day'].'</td>';    
        echo '<td>'.$row['period'].'</td>';
        echo '<td>';

            $sql = "SELECT 
                    *
                    FROM ts_roompref
                    WHERE request_id=:request_id";
            $stm = $pdo->prepare( $sql );
            $stm->execute( array( ':request_id' => $row_id ) );
            $rows = $stm->fetchAll();           
    foreach ($rows as $row) 
            {
                if ($row['room_id']!="0")
                    echo $row['room_id'].'<br>';
            }

        echo '</td>';

        echo '<td>';

        $sql = "SELECT 
                        *
                        FROM ts_allocation
                        WHERE request_id=:request_id";
        $stm = $pdo->prepare( $sql );
        $stm->execute( array( ':request_id' => $row_id ) );
        $rows = $stm->fetchAll();           
        foreach ($rows as $row) 
        {
            echo $row['status'];
        }

        echo '</td></tr>';
        };

1 个答案:

答案 0 :(得分:1)

您正在为foreach数组使用$rows循环,并在其中覆盖$rows变量。所以只需为内部循环使用另一个变量名称:

$rows = $stm->fetchAll();
foreach ($rows as $row)
{
    // ...
    $rows2 = $stm->fetchAll();
    foreach ($rows2 as $row2)
    {
        // ...
    }
}