简体   繁体   English

从数据库中获取更多数据

[英]Fetching more data from database

I have a list of data or "quotes" that are being displayed, I only limited 10, but I want more to show.... 我有一个要显示的数据或“引号”的列表,我只限制了10个,但是我想显示更多。

<ul class="recent-list">
  <?php 
    require("inc/connect.php");
    $result = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT 0, 20", $link);
    while($row = mysql_fetch_array($result)){
  ?>

    <li id="<?php echo $row['id']; ?>" class="quote-wrap group">
      <span>
        some stuff here....           
      </span>

      <div class="quote">

        <p>
          <?php echo htmlentities($row['quote']); ?>
        </p>

      </div><!-- /.quote -->
    </li>

  <?php } ?>
</ul>

Then on the bottom of the list, there is a link of "Show more", where the data that is being displayed fades away and the next set of data appears. 然后,在列表的底部,有一个“显示更多”的链接,正在显示的数据逐渐消失,并显示下一组数据。

I think I understand the "ajax" part. 我想我了解“ ajax”部分。 It'd look something like this. 看起来像这样。

$(document).delegate("'#load-more'", "click", function(){


        $.post("load-more.php", $(this).serialize(), function(data) {
                   // success?
   });
});

Where load-more.php is the file I need to create to load in more data, and run mysql queries. 我需要创建load-more.php文件来加载更多数据,并运行mysql查询。 That part is what confusing me. 那部分让我感到困惑。

After clicking the "show more" link, how can I fetch the next set of data with PHP? 单击“显示更多”链接后,如何使用PHP获取下一组数据? I'm new to PHP and ajax so this is a hard one for me. 我是PHP和Ajax的新手,所以这对我来说很难。

OK! 好! So first thing to do is create an external PHP file with the code for getting data from the database. 因此,第一件事就是使用代码从数据库中获取数据来创建一个外部PHP文件。

This file should have the ability to be passed a $_POST or $_GET variable with the starting index that you want to query records from. 该文件应该能够传递带有要从中查询记录的起始索引的$ _POST或$ _GET变量。 It should look something like this: 它看起来应该像这样:

require("inc/connect.php");
$start = $_GET['start'];
$limit = $_GET['limit'];

We define the $start variable, which will hold the value of the first ID that should be returned in the query. 我们定义$ start变量,该变量将保存应在查询中返回的第一个ID的值。 Then the $limit variable which holds the number of rows to get from the database. 然后,$ limit变量保存要从数据库获取的行数。

$result = 
mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT $start, $limit", $link);

Then we construct and execute the query using these variables. 然后,我们使用这些变量构造并执行查询。 At this stage it starts getting a little more complex. 在这个阶段,它开始变得更加复杂。

$data = array(); //We create an empty array to store the new values in.

while($row = mysql_fetch_array($result)){//Then we loop through the return results.
    //Each row variable is an object, should have two properties
    // $row['id'] & $row['quote']
    // So we add this object into our $data array.
    array_push($data, $record);
}
//Now PHP works some of it's magic and turns that $data array into something 
//that javascript can understand. A JSON string.
echo(json_encode($data));

When Javascript reads this string with it's AJAX call, it will be able to turn it back into an array of objects, which will still have the properties that the $row variable had. 当Javascript通过AJAX调用读取该字符串时,它将能够将其转换回对象数组,该对象数组仍具有$ row变量具有的属性。 In Javascript though, rather than referring to properties of an object with a ['property'] or ->property syntax like PHP, we use .property. 但是,在Javascript中,我们使用.property,而不是使用['property']或-> property语法(例如PHP)来引用对象的属性。

I'm being brave here, I don't know whether you have heard much about JSON, but there is plenty of support for it on the internet if you look around. 我在这里很勇敢,不知道您是否听说过JSON,但是如果您四处看看,互联网上对此有很多支持。 It is incredibly useful to understand. 理解它非常有用。 Basically we have just used PHP to create an array of objects with the properties id and quote in both. 基本上,我们刚刚使用PHP创建了具有属性id和quote的对象数组。 And then we echo it out as a JSON string. 然后我们将其作为JSON字符串回显。

So, if we go to this URL: 因此,如果我们转到以下URL:

http://localhost/quotes.php?start=0&limit=10

Then we should see a page that looks something like this: 然后,我们应该看到一个页面,看起来像这样:

[
    {
        "id":0,
        "quote":"The first quote."
    },
    {
        "id":1,
        "quote":"The second quote."
    },
    {
        "id":2,
        "quote":"The third quote."
    },
    ...
]

Now it won't be formatted that well, but if you run it through a JSON formatter (google it). 现在,它的格式可能不会很好,但是如果您通过JSON格式程序(google)运行它。 Then it should resemble something similar to that. 那么它应该类似于类似的东西。 Make sure it works before you carry on! 在继续进行之前,请确保它能正常工作!

Then, I would remove the embedded PHP from your page, and get everything with AJAX using the PHP script that you have just written. 然后,我将从您的页面中删除嵌入式PHP,并使用您刚编写的PHP脚本使用AJAX来获取所有内容。

Next, create a jQuery function that sends an AJAX request to the PHP file. 接下来,创建一个jQuery函数,将一个AJAX请求发送到PHP文件。 Something like: 就像是:

function getQuotes(start, limit) {
    //Clear the recent list element
    $(".recent-list").html("");
    $.ajax({
        url:"http://localhost/quotes.php?start="+start+"&limit="+limit,
        success: function (data) {
            data = eval(data);
            //Data should now be a javascript array of objects.
            for(i=0;i<data.length;i++) {
                $(".recent-list").append("<li id='"+data[i].id+"' class='quote-wrap-group'><li>");
                $("#"+i).html("<div class='quote'><p>"+data[i].quote+"</p></div>");
            }
        }
    });
}

I am aware that last function could look a bit confusing, an AJAX request is made to your PHP page, the data is collected and turned into an array. 我知道最后一个函数可能看起来有些混乱,对您的PHP页面进行了AJAX请求,收集了数据并将其转换为数组。 We loop through the array, and insert the values into the page in the same way that you had it configured earlier. 我们遍历数组,并以与您先前配置的相同方式将值插入页面。

If you contain the current index in a variable called currentIndex, then you can know what index to request next. 如果将当前索引包含在名为currentIndex的变量中,则可以知道接下来要请求的索引。 You can use this variable to decide which is the next index to pull down with something like 您可以使用此变量来确定哪个是下一个下拉索引,例如

getQuotes(currentIndex+10, 10);

This can all be chained together with a button somewhere on the page, eg 所有这些都可以通过页面上某个位置的按钮链接在一起,例如

<button id="more">Get more quotes</button>

Then at the top of your Javascript section: 然后在Javascript部分的顶部:

$(document).ready(function(){
    $("more").click(function(){
        getQuotes(currentIndex+10, 10);
        currentIndex += 10;
    });
});

This creates a function so that whenever you click on the button the old results are removed from the and the new ones are added, also incrementing the currentIndex so that it stays correct. 这会创建一个函数,以便每当您单击按钮时,都会从中删除旧结果,并添加新结果,同时还会增加currentIndex以使其保持正确。

Although this might seem like a complicated way to do it, if you learn this technique it will simplify a whole lot in terms of debugging and future projects. 尽管这似乎是一种复杂的方法,但是如果您学习此技术,它将在调试和将来的项目方面简化很多工作。 So it is worth sticking with this to see if you can get it working. 因此,值得一试,看看是否可以正常使用。

Another thing I would note is that if this data is sensitive then you should be using $_POST variables (jQuery supports them still), and if there is a large amount of data you should be capping the limit in the PHP file. 我要注意的另一件事是,如果此数据敏感,则应使用$ _POST变量(jQuery仍支持它们),并且如果有大量数据,则应限制PHP文件中的限制。

Finally, all of this code was written in Stack Overflow, off the top of my head so there might be something wrong. 最后,所有这些代码都是用Stack Overflow编写的,离我很近,所以可能出了点问题。 I hope you can get this sorted, and I hope this helped you! 希望您能解决这个问题,希望对您有所帮助!

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

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