0

In the below code when I var_dump($result) I can see the data I want is in there... but I have yet to be able to get to it.

Code:

try {   
    $query = new dbquery(Connection::make($dbconfig['dbinfo']));
    $count = $query->runSQL("select count(*) from table_name");

    $result = $count->fetchAll();
    var_dump($result);
    echo $result[0];
    echo $result[1];
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

SQL:

public function runSQL($sql, $params = NULL) {
    //Prepares the SQL Statement you pass through
    $statement = $this->pdo->prepare($sql);

    //Binds the Parameters I pass through on execute, so no need for seperate $statement->bindParam()
    $statement->execute($params);

    //Returns the statement.
    return $statement; 
}

output of var_dump:

array(1) { [0]=> array(2) { ["count(*)"]=> string(1) "3" [0]=> string(1) "3" } } Array

it's the ["count(*)] key I need, the value 3

I've tried the below and none gives me the right value:

echo $result[0];
echo $result[1];
echo $result['count(*)'];

Can anyone please advise where I am going wrong, all i want to know is the number of rows.

Barry
  • 3,216
  • 7
  • 22
  • 42
TheOne745665
  • 367
  • 4
  • 11

3 Answers3

1

You are getting array inside an array as result. You can do the following:

echo $result[0][0];

OR

echo $result[0]['count(*)'];

Note that it is a good habit to do Aliasing in the query, for better readability. For eg, COUNT(*) can be aliased as total_count:

$count = $query->runSQL("select count(*) AS total_count from table_name");

Now, you can access the total row count as follows:

echo $result[0]['total_count'];
Madhur Bhaiya
  • 27,326
  • 10
  • 44
  • 54
1

You need to avoid use of fetchAll in cases that only returns 1 row (COUNT, SUM or any group functions)

You can use

echo $result[0][0];

Or

$result = $count->fetchOne(); #or $count->fetch(); read the docs to the right method
echo $result[0];
João Neto
  • 115
  • 1
  • 5
0

The SQL command to get the number of rows is

select count(*) as alias from table_name
576i
  • 6,409
  • 6
  • 48
  • 84
Karma Blackshaw
  • 773
  • 5
  • 19