Count number of php rows

1

I'm trying to count the number of rows based on a WHERE in php but when I execute it it throws me an error.

Code to count

public function mostrarRollosModel($tabla){

        $stmt = Conexion::conectar() -> prepare("SELECT cod_parte FROM $tabla WHERE es_rollo='S'");
        $stmt->execute();
        $stmt -> fetchAll();
        $numero_filas = mysqli_num_rows($stmt);
        return $numero_filas;
        $stmt->close();
    }

Error that launches

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given in C:\xampp\htdocs\Inventarios\models\Rollos.php on line 13

How can I resolve this error? Thanks

    
asked by Baker1562 20.03.2018 в 22:35
source

1 answer

2

You are mixing code from two different APIs: mysqli and PDO.

The error message in your comment indicates that you are using PDO. Then to get the number of rows you can use rowCount :

public function mostrarRollosModel($tabla){

        $stmt = Conexion::conectar() -> prepare("SELECT cod_parte FROM $tabla WHERE es_rollo='S'");
        $stmt->execute();
        //$stmt -> fetchAll(); No es necesario si usas rowCount()            
        $numero_filas = $stmt-rowCount();
        $stmt->close();
        return $numero_filas;

In the code I have corrected two more things:

  • I have put everything object oriented, because in this line $numero_filas = mysqli_num_rows($stmt); were using the procedural mode. The mixture of styles is discouraged.
  • I have closed $stmt before return . What is after return is not executed.
  • If you use rowCount() it is not necessary to use fetchAll . And if you use fetchAll , you can dispense with the use of rowCount . For example:

        $arrDatos=$stmt -> fetchAll();             
        $numero_filas = count($arrDatos);
    

    This form is convenient if at the same time you are going to work with the data. Since you avoid a supplementary call to rowCount . Counting how many rows has the array that returns fetchAll you already know how many rows there are.

answered by 20.03.2018 / 22:42
source