Problem with fetch (PDO :: FETCH_ASSOC)

0

I have a small login form, with the variables $ user and $ password that have the correct values, the problem is that it gives me

  

Fatal error: Call to a member function rowCount () on boolean

that is, as if the array were empty and I have no idea why. Here I leave the code (obviously everything is enclosed in the php tags):




  include("conectarBD.php");

  $usuario = $_POST['user'];
  $contrasena = $_POST['pass'];

  if (isset($usuario) && !empty($usuario) && isset($contrasena) && !empty($contrasena)) {
    $sql = "SELECT usuario, contrasena FROM usuarios WHERE usuario == :usuario";
    $statement = $conn->prepare($sql);
    $statement->execute(array(':usuario'=>$usuario));
    $getUser = $statement->fetch(PDO::FETCH_ASSOC);

    $total = $getUser->rowCount();
    if ($total = 0) {
      echo "Nothing";
    }
}

    
asked by Power_HR 06.11.2016 в 18:31
source

3 answers

4

This way you will work rowCount() :

$sql = "SELECT usuario, contrasena FROM usuarios WHERE usuario = :usuario";
                                          // No es == si no = ^^^ 
$statement = $conn->prepare($sql);

$statement->execute(array(':usuario'=>$usuario));

$getUser = $statement->fetch(PDO::FETCH_ASSOC);

$total = $statement->rowCount();

if ($total > 0) {
//        ^^^ no se compara con =
   echo "Hay cosas";

} else {

   echo "No hay nada";
}
    
answered by 06.11.2016 / 18:55
source
1

The answer to what I saw in your code is this:

        $query = "SELECT * FROM usuarios WHERE usuario= :username AND contrasenia = :pass";
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':username', $usuario, PDO::PARAM_STR);
        $stmt->bindParam(':pass', $contrasenia, PDO::PARAM_STR);
        $stmt->execute();
        //obtenemos los resultados
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        //Obtenemos el conteo de filas
        $filas = count($result);
        //Obtenemos el conteo de otra forma
        $filas = $stmt->rowCount();

One of the observations that I saw in your code, is that when doing the comparison you used the == operator when it should not be that.

    
answered by 06.11.2016 в 20:39
0
$statement->fetch(PDO::FETCH_ASSOC);

Returns a common associative array (a map). It is not an object, it does not contain any method rowCount() . To get the amount of data that contains an array or map, use count ()

I think you're confused with the method offered by the statement object In your case, you could invoke it with

$statement->rowCount();

However, is not recommended to be used to get the number of rows returned by a SELECT:

  

If the last SQL statement executed by the PDOStatement object   associated was a SELECT statement, some databases could   return the number of rows returned by that statement. But nevertheless,   this behavior is not guaranteed for all databases   and you should not rely on it for portable applications.

    
answered by 06.11.2016 в 18:49