php return停止循环

时间:2019-02-24 03:37:05

标签: php loops for-loop

美好的一天,我编写了一个函数,该函数要显示与上周日期匹配的记录,但它只会循环一次。有没有一种方法可以返回所有日期并显示所有与日期匹配的记录?这是我的代码。

function fetch_week(){

$today = date('F d Y');

for($i = 1; $i <= 7; $i++)
{
    $repeat = strtotime("-1 day",strtotime($today));
    $today = date('F d Y',$repeat);
    $output = '';
    $conn = mysqli_connect("localhost", "root", "", "sample");
    $sql = "SELECT * FROM list WHERE datee = '".$today."' ORDER BY id DESC";
    $result = mysqli_query($conn, $sql);
    if(empty(mysqli_num_rows($result))){
    echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
    }
    else{

    while($row = mysqli_fetch_assoc($result)){

    $output .= '<tbody id="appTable">
                <tr class="content" style="font-weight: normal text-align: center">  
                      <td>'.$row["name"].'</td>  
                      <td>'.$row["address"].'</td> 
                      <td>'.$row["contact"].'</td>
                      <td>'.$row["datee"].'</td> 
                </tr>  
             </tbody>
                      ';

    }
    return $output;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以创建一个数组,并在循环结束后返回它。检查以下代码:

function fetch_week() {

    $today = date('F d Y');
    $response = [];
    for ($i = 1; $i <= 7; $i++) {
        $repeat = strtotime("-1 day", strtotime($today));
        $today = date('F d Y', $repeat);
        $output = '';
        $conn = mysqli_connect("localhost", "root", "", "sample");
        $sql = "SELECT * FROM list WHERE datee = '" . $today . "' ORDER BY id DESC";
        $result = mysqli_query($conn, $sql);
        if (empty(mysqli_num_rows($result))) {
            echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
        } else {
            $output = '<tbody id="appTable">';
            while ($row = mysqli_fetch_assoc($result)) {

                $output .= '<tr class="content" style="font-weight: normal text-align: center">  
                      <td>' . $row["name"] . '</td>  
                      <td>' . $row["address"] . '</td> 
                      <td>' . $row["contact"] . '</td>
                      <td>' . $row["datee"] . '</td> 
                </tr>';
            }
            $output .= '</tbody>';
            $response[] = $output;
        }
    }
    return $response;
}

您需要遍历输出以打印数据。但是除了所有这些,您的代码还可以广泛用于SQL注入。请小心,并为此进行更改。同样,您不需要一次又一次地在循环中创建tbody。您只能第一次在上面的代码中进行过更改。

希望它对您有帮助。