php - MySQL:使用同一网页更新列项目

标签 php mysql database dynamic limit

我的数据库中目前有一个包含数十个项目的表。我现在的 PHP 页面,标记为firstpage.php,使用 LIMIT 4 一次仅显示数据库中的 4 个项目。我想使用相同的页面,firstpage.php,并有一个显示“下一步”的按钮,所以当用户单击该按钮,将显示数据库中接下来的 4 个项目,直到没有更多项目为止。

这是我的代码:

<?php

require("database.php");

$start = (isset($_GET['start']) ? (int)$_GET['start'] : 0);

$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT $start, 4;");
    if (!$result) {
        printf("Error: %s\n", mysqli_error($con));
        exit();
    }

echo "<table width='1024' border='0' cellpadding='10' cellspacing='5' align='center'>
<tr>
<th></th>
<th>Menu Items</th>
<th>Description</th>
<th>Price</th>
<th>Add to Order</th>
</tr>";

 while($row = mysqli_fetch_array($result))
 {
  echo "<tr>";
  echo "<td align='center'><img src=\"" . $row['picturepath'] . "\" /></td>";
  echo "<td align='center'>" . $row['name'] . "</td> <td align='center'> <input type='button' value='More Info'; onclick=\"window.location='more_info.php?';\"> </td>";
  echo "<td align='center'>" . $row['price'] . "</td> <td align='center'> <input type='button' value='Add to Order' onclick=''> </td>";
  echo "</tr>";
 }
echo "</table>";

mysqli_close($con);


echo "<table width=\"1024\" align=\"center\" >";
    echo "<tr height=\"50\"></tr>";
            $next = $start + 4;
    echo '<a href="?start="'.$next.'">Next items</a>';

echo "</table>";

?>

到目前为止,“NEXT”链接尚未加载接下来的 4 项。不知道我做错了什么。

最佳答案

有数千个关于它的教程,但我只想给出 您已经了解了如何操作的基本概念,因此您会发现它既简单又容易。

SQL 限制

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

(来自:http://dev.mysql.com/doc/refman/5.0/en/select.html)

逻辑部分

我们需要指示从哪一行开始计数(我们称之为开始), 顺便说一下,计数将是一个常数值(在您的情况下 - 4)。 “更多”链接将帮助我们。

$start = (isset($_GET['start']) ? (int)$_GET['start'] : 0);
//the query and the loop (remember to use the expanded format of LIMIT: LIMIT $start,4)

按钮或链接(通常是链接)的值为 start 加 4:

$next = $start + 4;
echo '<a href="?start="'.$next.'">Next 4 items</a>';

我希望您掌握了基本想法,并且能够自行继续。

关于php - MySQL:使用同一网页更新列项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20381398/

相关文章:

PHP cafile 工作,capath 不工作 (Linux)

mysql - 关系数据库 : Variable Fields

php - MySQLi 对象问题

c# - 来自同一张表的 3 个不同的不同值

json - 加载 JSON 文件与查询 MongoDB

MySQL:三个相互关联的表

php - 使用 $query = mysql_query 选择更多表

php - 将特定日期的多个时差相加

php - 在 Yii 1.1.16 QueryBuilder 中的 SELECT 之前添加 SET STATEMENT

mysql - INSERT INTO ... SELECT 不详细说明所有列