PDO error - Call to a Member functio on null

Asked

Viewed 40 times

0

I created a function to make a query in the BD and return a User from the variable $nome passed by parameter, however, when testing it enters the Else, someone would know where the error is?

Note: The PDO connection is working and there is a user with the test name inside the BD.

Function:

public static function obtemUsuarioPorNome($db,$nome){
        $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
        $stmt->bindParam(":nome", $nome);
        $stmt->execute();
        if($row = $stmt->fetch(PDO::FETCH_ASSOC) == $nome){
            extract($row);
            $usuario = new Usuario($id,$nome,$senha);
            return $usuario;
        } else {
            return null;
        }
    }

Test code:

$objUsuario = Usuario::obtemUsuarioPorNome($dblink,"barba-ruiva");
print("<p>".$objUsuario->getNome()." ".$objUsuario->getId()."</p>");
  • Error is on which line?

  • Apparently, instead of entering if, it is entering Else and returning null

  • If it falls on Else your connection is not valid or is void.

  • Just add if($row = $stmt->fetch(PDO::FETCH_ASSOC)).

  • error solved, thanks for the help

1 answer

0


You cannot compare the NAME with the FETCH_ASSOC result, as this returns to the ROW variable, an associative array containing the SELECT response data.

public static function obtemUsuarioPorNome($db,$nome) {
   $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
   $stmt->bindParam(":nome", $nome);
   $stmt->execute();
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   if(count($row) > 0) {
      // extract($row);
      $usuario = new Usuario($row["id"], $row["nome"], $row["senha"]);
      return $usuario;
   } else {
      return null;
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.