简体   繁体   English

在SQL查询中将JQuery变量用作OFFSET

[英]Use JQuery variable as OFFSET in SQL query

I am trying to implement an infinite scroll functionality for posts in a news feed. 我正在尝试为新闻提要中的帖子实现无限滚动功能。 The posts are loaded into the news feed as soon as the user reaches the footer. 用户到达页脚后,帖子便立即加载到新闻提要中。


The Problem 问题

Every time the ajax call is executed I would like to increase the offset of the query . 每次执行ajax调用时,我都想增加查询的偏移量 I want to transfer the jquery offset variable somehow to php and the SQL query. 我想以某种方式将jquery偏移量变量传递给php和SQL查询。


The Code 编码

 // Infinite Scroll var offset = 0; if($(window).scrollTop() >= $('.post-wrapper').offset().top + $('.post-wrapper').outerHeight() - window.innerHeight) { if (element_in_scroll("footer")) { $('div.loadmoreajaxloader').show(); $.ajax({ url: '<?= Config::get('URL'); ?>index/loadPosts', success: function(data) { if(data) { $(".post-wrapper").append(data); $('div.loadmoreajaxloader').hide(); offset++; } else { $('div.loadmoreajaxloader').html('<center>Es sind keine weiteren Posts vorhanden.</center>'); } } }); } }); 

The Query 查询

 $query = $database->prepare("SELECT * FROM posts LIMIT 1 OFFSET $offset"); $query->execute(); return $query->fetchAll(); 


The offset increments as I would like it to, in the jquery code ( console.log(offset) ouputs 1, 2, 3 and so on...). 偏移量按照我想要的方式在jquery代码中递增( console.log(offset)输出1、2、3等...)。 However, I cannot get this variable into the SQL query. 但是,我无法将此变量添加到SQL查询中。

I would be very thankful for any kind of help! 我将非常感谢您提供的任何帮助!

You are not sending javascript variable offset in your ajax request 您没有在ajax请求中发送javascript变量offset

Change following line: 更改以下行:

url: '<?= Config::get('URL'); ?>index/loadPosts',

to: 至:

url: '<?= Config::get('URL'); ?>index/loadPosts?offset=' + offset,

Prevent SQL injections: 防止SQL注入:

$query = $database->prepare("SELECT * FROM posts LIMIT 1 OFFSET :offset");
$query->execute(array(':offset' => $offset));

return $query->fetchAll();
  1. Pass the offset value in AJAX . AJAX传递offset值。
  2. GET the offset value in your PHP file 在您的PHP文件中GET offset

     // Infinite Scroll var offset = 0; if($(window).scrollTop() >= $('.post-wrapper').offset().top + $('.post-wrapper').outerHeight() - window.innerHeight) { if (element_in_scroll("footer")) { $('div.loadmoreajaxloader').show(); $.ajax({ url: '<?= Config::get('URL'); ?>index/loadPosts?offset='+offset, success: function(data) { if(data) { $(".post-wrapper").append(data); $('div.loadmoreajaxloader').hide(); offset++; } else { $('div.loadmoreajaxloader').html('<center>Es sind keine weiteren Posts vorhanden.</center>'); } } }); } } 

In PHP File 在PHP文件中

$offset = $_GET['offset'];
$query = $database->prepare("SELECT * FROM posts LIMIT 1 OFFSET $offset");
$query->execute();

return $query->fetchAll();

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

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