MySQLi/Prepared Statements&SQL_CALC_FOUND_ROWS

cos*_*ari 6 mysqli prepared-statement sql-calc-found-rows

我目前正在探讨如何使用预准备语句实现SQL_CALC_FOUND_ROWS.

我正在写一个分页类,显然我想在查询中添加LIMIT,但也要查找总行数.

这是该课程的一个例子.

$query="select SQL_CALC_FOUND_ROWS id,title,location,salary,employer from jobs where region=38 limit 0,3";

if($stmt = $connection->prepare($query)) {
            $stmt->execute()or die($connection->error); //execute query
            $stmt->bind_result($id,$title,$location,$salary,$employer,$image);
            while($stmt->fetch()){
                $jobs[$x]['id']=$id;
                $jobs[$x]['title']=$title;
                $jobs[$x]['location']=$location;
                $jobs[$x]['salary']=$salary;
                $jobs[$x]['employer']=$employer;
                $jobs[$x]['image']=$image;
                $x++;
            }
            $stmt->close();//close statement
        }
Run Code Online (Sandbox Code Playgroud)

关于如何获取SQL_CALC_FOUND_ROWS实际值,我有点难过?我曾想过添加以下内容:

            $stmt->store_result();
            $count=$stmt->num_rows;
Run Code Online (Sandbox Code Playgroud)

但是这只给出了一个基于LIMIT的数字,所以在上面的例子中它应该是3而不是完整的6.

希望有道理.

cos*_*ari 9

为了解决这个问题,我将详细解释下面对任何对未来感兴趣的人的答案.

原始代码

$query="select SQL_CALC_FOUND_ROWS id,title,location,salary,employer from jobs where region=38 limit 0,3";

if($stmt = $connection->prepare($query)) {
        $stmt->execute()or die($connection->error); //execute query
        $stmt->bind_result($id,$title,$location,$salary,$employer,$image);
        while($stmt->fetch()){
            $jobs[$x]['id']=$id;
            $jobs[$x]['title']=$title;
            $jobs[$x]['location']=$location;
            $jobs[$x]['salary']=$salary;
            $jobs[$x]['employer']=$employer;
            $jobs[$x]['image']=$image;
            $x++;
        }
        $stmt->close();//close statement
    }
Run Code Online (Sandbox Code Playgroud)

更新的代码

$query="select SQL_CALC_FOUND_ROWS id,title,location,salary,employer from jobs where region=38 limit 0,3";

if($stmt = $connection->prepare($query)) {
        $stmt->execute()or die($connection->error); //execute query
        $stmt->bind_result($id,$title,$location,$salary,$employer,$image);
        while($stmt->fetch()){
            $jobs[$x]['id']=$id;
            $jobs[$x]['title']=$title;
            $jobs[$x]['location']=$location;
            $jobs[$x]['salary']=$salary;
            $jobs[$x]['employer']=$employer;
            $jobs[$x]['image']=$image;
            $x++;
        }
            //get total number of rows.
            $query="SELECT FOUND_ROWS()";
            $stmt = $connection->prepare($query);
            $stmt->execute();
            $stmt->bind_result($num);
            while($stmt->fetch()){
                $count=$num;
            }

        $stmt->close();//close statement
    }
Run Code Online (Sandbox Code Playgroud)

可能可以用另一种方式做得更好,但似乎无法在网上找到任何好的例子,这有效!

  • 您不需要使用"while",因为它只返回一行 (2认同)