Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere il valore SQL_CALC_FOUND_ROWS utilizzando le istruzioni preparate?

Riuscito a capirlo, descriverò in dettaglio la mia risposta di seguito per chiunque sia interessato al futuro.

Codice originale

$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
    }

Codice aggiornato

$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
    }

Probabilmente si potrebbe fare meglio in un altro modo, ma sembra che non si trovino buoni esempi da nessuna parte online e questo funziona!