Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for mysql_num_rows using PDO

Tags:

php

mysql

pdo

Right now I have a PHP file that does a MYSQL query and then counts rows like this:

$count=mysql_num_rows($result);


if ($count == 1) {
    $message = array('status' => 'ok');
} else {
    $message = array('status' => 'error');
}

This works fine but I'm trying to change all my PHP files to use PDO. So how can this be done with PDO?

like image 721
user1323294 Avatar asked Jul 03 '12 05:07

user1323294


Video Answer


4 Answers

$res = $DB->query('SELECT COUNT(*) FROM table'); $num_rows = $res->fetchColumn(); 

or

$res = $DB->prepare('SELECT COUNT(*) FROM table'); $res->execute(); $num_rows = $res->fetchColumn(); 

You can use this to ask if data exists or is selected, too:

$res = $DB->query('SELECT COUNT(*) FROM table'); $data_exists = ($res->fetchColumn() > 0) ? true : false; 

Or with your variables:

$res = $DB->query('SELECT COUNT(*) FROM table'); $message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error'); 
like image 92
WolvDev Avatar answered Sep 21 '22 13:09

WolvDev


$stmt = $db->query('SELECT * FROM table');   $row_count = $stmt->rowCount();   echo $row_count.' rows selected'; 
like image 22
sekhar Avatar answered Sep 24 '22 13:09

sekhar


Maybe you can use PDO's "fetchAll" method, which returns an array containing all the SELECT results. Then use "count" method to count the array's rows.

Ex:

$rows = $stmt->fetchAll();
$num_rows = count($rows);
like image 45
priki Avatar answered Sep 25 '22 13:09

priki


If you are not using prepared statements then try:

$find = $dbh->query('SELECT count(*) from table');
if ($find->fetchColumn() > 0){
    echo 'found';
}

However, if you choose prepared statements, which i highly recommend, then:

$find = $dbh->prepare('SELECT count(*) from table');
$find->execute();
if ($find->fetchColumn() > 0){
    echo 'found';
}
like image 30
shxfee Avatar answered Sep 23 '22 13:09

shxfee