每次执行函数时增加 php 变量值

Increment php variable value every time a function is executed

我正在发送一个公式,它通过 PHP 从 MySQL 数据库中检索数据。我想一步一步地收集数据,通过滚动,一种用Javascript编写的"infinite scrolling"实现。它工作正常,除了我找不到增加指定从检索数据开始的行的变量值的方法,每次我从脚本内部调用 PHP 函数时在我的 HTML 文档中。

下面是index.php代码

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <!--script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script-->

    <script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/copy_code.js"></script>
    <script src="js/scroll.js"></script>    
    <script src="js/preloader.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">       

    <?php
    include("dbconnect.php");
    include("search.php");      
    ?>
</head>


<body>

     <!-- Preloader -->
    <div class="preloader"></div>

    <!-- scroll to top buttom -->
    <a href="#" id="scroll"><span></span></a>



<article>

    <div class="entry_content">


        <FORM method=post action='<?php echo htmlentities($_SERVER['PHP_SELF']); ?>'>

              <!-- My FORM -->

        </FORM>


        <div id="load_data"> </div>
        <div id="load_data_message"></div>


    </div>
</article>


</body>
</html>


<script>

$(document).ready(function(){


 var limit = 10;
 var start = 0;
 var action = 'inactive';
 console.log("Limite + Start:")
 console.log(limit);
 console.log(start);


 function load_data(limit, start)
 {
  console.log("Limite & Start");
  console.log(limit);
  console.log(start); 

  var data="<?php  echo search(limit, start);  ?>";


    $('#load_data').append(data);

    if(data == '') /* No data: active, "no data found" */
    {
     $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
     action = 'active';

    }
    else /* data: active, "Please wait..." */
    {

     $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
     action = "inactive";
    } 
 }


 if(action == 'inactive')
 {
  console.log("Inactiva");
  action = 'active';
  load_data(limit, start);
 }


 $(window).scroll(function(){

  if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
  {   
   action = 'active';
   console.log("Activaaaaaa. Start: ");
   start = start + limit; 
   console.log(start);    
   setTimeout(function(){
   load_data(limit, start);
   }, 1000);
  }
 });


});

</script>


search(limit, start) 函数在 search.php 文件中,它以这种方式检索值:

 $result = $mysqli->query("SELECT * FROM MyTable WHERE $conditions LIMIT $start, $limit");


while ($row = mysqli_fetch_object($result)) {
     echo [...]
}

每次从 index.php 调用 load_data(limit, start) 函数时,我都想增加这个 $start 变量。

我尝试创建 cookie(没用,因为我无法在刷新前获取新的 cookie 值),在搜索函数中创建一个静态 php 变量并增加它的值(没用,我不知道为什么),通过表单传递一个变量并增加它的值,...但没有任何效果。

我提到你可以在 javascript 中实现变量的增量,所以组合一个简单的基于 ajax 的无限滚动系统。为简单起见,没有数据库查询,但主要逻辑在那里

为了在页面加载后调用任何 PHP 函数,您需要使用 XMLHttpRequest(又名 Ajax 向某个脚本(或同一页面)发送 HTTP 请求) 或较新的 fetch api 并使用回调函数以某种方式附加响应。

在上面没有使用 ajax 所以初始页面加载静态 Javascript 变量被 PHP ( var data="<?php echo search(limit, start); ?>"; ) - 一旦那个结果集已被 javascript 函数使用,无法按原样获取下一组记录。使用标准形式 submit 是行不通的,所以我在上面的代码中看不到重点。

因为您需要做的就是使用 $start 变量来更改查询返回的结果,因此不需要任何会话或 cookie 存储 - 只需让 javascript 增加相关计数器即可.

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();


        $page=!empty( $_POST['page'] ) ? $_POST['page'] : 10;
        $limit=!empty( $_POST['limit'] ) ? $_POST['limit'] : 10;


        /* 
            call / query database to fetch the next portion of results.
            Here it is simply emulating the return of data
        */
        for( $i=0; $i < $limit; $i++ ){
            $sql=sprintf('select * from `table` order by id limit %d,%d', $page, $limit);
            printf( '<div>Record #%d from %s</div>', $i+1, $sql );
        }

        exit();
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Infinite scroller</title>
        <script>
            const setruntime=function( callback ){
                return document.addEventListener('DOMContentLoaded', callback );
            }

            const ajax=function(url,params,callback){
                let xhr=new XMLHttpRequest();
                xhr.onload=function(){
                    if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
                };
                xhr.open( 'POST', url, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
                xhr.send( params );
            };

            const initialise=function(){
                var page=limit=10;
                var status=true;

                const scrollhandler=function(e){
                    if( ( window.innerHeight + window.scrollY ) >= document.body.offsetHeight ){
                        const url=location.href;
                        const payload={
                            'action':'scroll',
                            'page':page,
                            'limit':limit
                        };
                        const callback=function(r){
                            /* process and add response data somehow... */
                            let form = document.forms.geronimo;
                                form.insertAdjacentHTML( 'beforeend', r )

                            /* increment the page variable for the NEXT request */
                            page += limit;
                            /* once again set status to true to permit new ajax request */
                            status=true;
                        };

                        /* prepare the querystring for the request */
                        let params=Object.keys( payload ).map( k=>{
                            return [k,payload[k]].join('=')
                        }).join('&');

                        /* send the request */
                        if( status ) ajax( url, params, callback );
                        status=false;
                    }
                }
                document.addEventListener( 'scroll', scrollhandler );
            };
            setruntime( initialise );
        </script>
        <style>
            body,body *{font-family:fantasy}
            div{width:50%;float:none;margin:5rem auto;padding:3rem;border:1px dashed rgba(1,1,1,0.1);background-color:rgba(255,253,225,1)}
            div:nth-child(even){background-color:rgba(255,243,243,1)}
        </style>
    </head>
    <body>
        <form name='geronimo' method='post'>
            <?php
                /* display the first X records, SCROLL to fetch subsequent X + PAGE records... */
                for( $i=1; $i < 10; $i++ )printf( '<div>%d</div>', $i );
            ?>
        </form>
    </body>
</html>