How to get the number of rows from a SELECT statement in PDO? [closed]

0

How do I know the number of records that returned me from a SELECT statement? I tried to use rowCount() but this did not work in my code, I just want it to return the amount just that.

$contador = $this->con->conectar()->prepare("SELECT * FROM login WHERE 'usuario' =:usuario AND 'senha' =:senha");
        $contador->bindPARAM(":usuario", $this->usuario, PDO::PARAM_STR);
        $contador->bindPARAM(":senha", $this->senha, PDO::PARAM_INT);
        $contador->execute();

        echo $contador->rowCount();
    
asked by anonymous 10.12.2017 / 17:47

3 answers

1

He may not understand your request, check the SQL syntax for warranty only, if it does not work try doing it this way:

// Cria objeto PDO
$conexao = new PDO('mysql:host=localhost;dbname=meuBanco', 'root', 'senhasenha');

// Query que será executada. Recebe o parâmetro :email
$query = "select * from login where usuario= :usuario AND senha = :senha";

// Prepara a query para execução
$consulta = $conexao->prepare($query, array(PDO::CURSOR_SCROLL));

// Atribui o parametro $email a :email na consulta
$consulta->bindParam(':usuario', $usuario,':senha',$senha);

// Executa a consulta ao banco de dados
$consulta->execute();

// Conta quantas linhas foram retornadas do banco de dados
$numero_linhas = $consulta->rowCount();
    
10.12.2017 / 21:28
1

I think rowCount() only works fine with UPDATE, DELETE, and INSERT

In the > > rowCount () - returns the number of rows affected by the last DELETE statement, INSERT or UPDATE executed.

Use PDOStatement :: fetchColumn () to retrieve the number of rows that will be returned.

$hostname="localhost";  
$username="USUARIO";  
$password="SENHA";  
$db = "NOME_DB";  
$conexao = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);

$nRows = $conexao->query("select count(*) from login where usuario='$usuario' and senha='$senha'")->fetchColumn(); 
    
10.12.2017 / 23:53
0

Try this way.

    $contador = $this->con->conectar()->prepare("SELECT * FROM login WHERE 'usuario' = :usuario AND 'senha' = :senha");
    $contador->bindValue(":usuario", $this->usuario);
    $contador->bindValue(":senha", $this->senha);
    $contador->execute();

    $numero = $contador->rowCount();
    echo $numero;
    
10.12.2017 / 18:45