How to see the amount of results with PDO

Asked

Viewed 236 times

0

Good night,

As use, I do to count the amount of results of a select in the database using PDO?

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-  requested-with');

include_once("conPDO.php");
$pdo = conectar();

$data = file_get_contents("php://input");
$data = json_decode($data);

$email = $data->email;
$senha = $data->senha;

$login=$pdo->prepare("SELECT * FROM usuarios WHERE email=:email AND senha=:senha");
$login->bindValue("email", $email);
$login->bindValue("senha", $senha);
$login->execute();

$count = $login->fetch(PDO::FETCH_NUM);
print_r($count);
  • try $nRows = $Pdo->query('select Count(*) from blah')->fetchColumn(); echo $nRows;

1 answer

2


One of the ways I would use to do this count without affecting the records would be with FETCH_ASSOC.

Try to do so instead of FETCH_NUM use $login->fetch(PDO::FETCH_ASSOC); and assign to $result. Then do count($result) and you will have the number of elements in the return array. That is the number of rows. This way you can take the total number without touching the amount of records or the template you are returning.

  • Just Count($result)? Nothing is missing in this part?

  • 1

    No, it would be something like if(count($result) > 0) { ..... }

  • Remembering that you will assign the login value to the $result, as in $result = $login->fetch(....)

  • Anything you can refer to the Count manual also http://php.net/manual/en/function.count.php

Browser other questions tagged

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