简体   繁体   English

如何遍历并一次显示1个DB记录?

[英]How can I loop through and display 1 DB record at a time?

I'm making a simple item picking system in which the user will use a button that will display an item and then once picked will be pressed and display the next item in the next row. 我正在制作一个简单的项目拣选系统,在该系统中,用户将使用一个按钮来显示一个项目,然后将其按下,然后在下一行中显示下一个项目。

Currently, when the button is pressed it will show the first item, then once pressed again will show the first item along with the second item, then third and so on. 当前,当按下按钮时,它将显示第一项,然后再次按下将显示第一项以及第二项,然后显示第三项,依此类推。

An example would be: 一个例子是:

first press: item1 第一次按下:item1

second press: item1, item2 第二次按下:item1,item2

I need to figure out how to display just one item at a time while it's going through the table. 我需要弄清楚如何在通过表格时一次仅显示一项。 Any help would be appreciated, thank you. 任何帮助,将不胜感激,谢谢。 Here's my button: 这是我的按钮:

<script>
var offset = 0;

 $(document).ready(function () {
$('#button1').click(function (e) {
    $("#div1").empty();
          // pass offset value with GET request
    $.getJSON("getItem.php?offset=" + offset,     function(result){

      offset++; // increment the value after sucessful AJAX call
      $.each(result, function(i, field){
        $("#div1").empty();

    $("#div1").append(JSON.stringify(result));     
      });
    });
  });
});
</script>

Here's my getitem.php 这是我的getitem.php

mysqli_select_db($con,"items");
$rows = null;
// Get the offset value
$offset = empty($_GET['offset']) ? 0 : $_GET['offset'];

$sql="SELECT * FROM items Limit 1, $offset "; // pass the offset value to LIMIT query

$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
$rows[] = array_map('utf8_encode', $row);

echo json_encode($rows);

The problem is the LIMIT section of your query. 问题出在查询的LIMIT部分。 The first part where you put "1" is actually the offset and the second one where you got $offset is the count value. 您放置“ 1”的第一部分实际上是偏移量,而获得$ offset的第二部分实际上是计数值。

It probably should be something like that: 可能应该是这样的:

$sql="SELECT * FROM items LIMIT $offset, 1";

You can select all your items from DB the first time and store them into an array. 您可以第一次从数据库中选择所有项目,然后将它们存储到阵列中。 Every time the user click the button, you can use the offset to select the item from that array. 每次用户单击按钮时,都可以使用偏移量从该数组中选择项目。

In this way you avoid to make a new http request for every object/click. 这样,您可以避免对每个对象/单击都发出新的http请求。 Unless you have an infinite number of objects and/or the object size is very large. 除非您有无限数量的对象和/或对象尺寸很大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM