gpt4 book ai didi

PHP For 循环与 Mysqli 的问题

转载 作者:行者123 更新时间:2023-11-29 13:09:01 24 4
gpt4 key购买 nike

我正在尝试让这个 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

关于PHP For 循环与 Mysqli 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com