簡體   English   中英

PHP For Mysqli的循環問題

[英]PHP For loop issue with Mysqli

我正在嘗試使用這個PHP腳本來分頁從mysql數據庫中提取的數據。

它在第二個for循環中的某個地方出錯了。 而不是通過它拉動數據只是返回空白或空字段。

我需要它來顯示數據庫中的標題,描述和內容字段以及ID。

        require_once("../controls/config.php");
        $connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        if ($connection->connect_errno) {
            printf("Connect failed: %s\n", $connection->connect_error);
            exit();
}

        // number of results to show per page
        $per_page = 3;

        // figure out the total pages in the database
        $result = $connection->query("SELECT * FROM pages");
        $total_results = $result->num_rows;
        $total_pages = ceil($total_results / $per_page);

        // check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
        if (isset($_GET['page']) && is_numeric($_GET['page']))
        {
                $show_page = $_GET['page'];

                // make sure the $show_page value is valid
                if ($show_page > 0 && $show_page <= $total_pages)
                {
                        $start = ($show_page -1) * $per_page;
                        $end = $start + $per_page; 
                }
                else
                {
                        // error - show first set of results
                        $start = 0;
                        $end = $per_page; 
                }               
        }
        else
        {
                // if page isn't set, show first set of results
                $start = 0;
                $end = $per_page; 
        }

        for ($i = 1; $i <= $total_pages; $i++)
        {
                echo "<a href='?page=$i'>$i</a><br>";
        }

        // loop through results of database query, displaying them in the table 
        for ($i = $start; $i < $end; $i++)
        {
                // make sure that PHP doesn't try to show results that don't exist
                if ($i == $total_results) { break; }

                echo $i["id"].' ';
                echo $i["title"].' ';
                echo $i["description"].' ';
                echo $i["content"].' ';
                echo '<a href="edit.php?id='.$i["id"].'">Edit</a> ';
                echo '<a href="delete.php?id='.$i["id"].'">Delete</a><br>';

        }

?>
<p><a href="new.php">Add a new record</a></p>

誰能指出我正確的方向?

看起來你正試圖將$ i視為一個關聯數組。 雖然$ i只是一個整數。 此外,您沒有包含mysqli查詢結果的數組。 你應該試試:

// this will loop through results and assign to $rows array
while($row = $result->fetch_array())
{
   $rows[] = $row;
}

// this will loop through $rows array and provide each column result
foreach($rows as $row)
{
    echo $row["id"];
    echo $row["title"];
    echo $row["description"];
    echo $row["content"];
}

有關詳細信息,請參閱: http//us2.php.net/mysqli_fetch_array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM