fetchColumn vs. columnCount

2

colsulta SELECT that a single record should return if it exists,

what's valid with

if ($stmtStore->fetchColumn ()==0){...} and the redultado is true

and the valid one with

if ($stmtStore->columnCount ()==0){...} and the result is false

according to the definitions

columnCount - Returns the number of columns in a result set.

fetchColumn - Returns a single column of the next row in a result set.

I do not understand the description

What I need is to validate if the SELECT returns the row or not, I have already used the function fetchColumn in the development of an application and I get doubts.

Thank you.

    
asked by Juan Carlos 01.12.2018 в 02:04
source

1 answer

1

To validate if there are records, the correct thing to do is to use fetchColumn .

The key is the way you write the query. This type of validation is done by counting the total rows, something like this:

SELECT COUNT(*) total FROM tabla;

That query will return a single column total with the total rows found, now you can use fetchColumn() :

$totalFilas=$stmt->fetchColumn();

if ($totalFilas > 0){
    //Hay registros
}

As for columnCount , as its name implies, it is to obtain the number of columns of a result. In the case above, it will always return 1 , if PDOStatement exists, regardless of whether there are rows or not, because what it does is count the total of columns, not the total rows.

It is clearly explained in the PHP Manual :

  

Return values

     

Returns the number of columns in the result set represented   by the object PDOStatement , even if the result set   It's empty . If there were no result set,    PDOStatement::columnCount() returns 0.

Be careful not to be confused by this statement: If there is no result set, PDOStatement::columnCount() returns 0. That does not mean there are no rows in the result, but that PDOStatement be NULL or FALSE because it was not created correctly or because it was closed before invoking the method.

    
answered by 01.12.2018 в 02:12