Incorrect Data to Get COUNT value of a query with rowCount PDO - PHP

2

I'm doing a query on the model of a web application in PHP with MVC . The idea is to make a query in which to put the value in empresa_id I see the total rows with that company, for this I used COUNT() in the query SQL .

The error that throws me is that company 14 has for example 8 users, and the function only shows me a 1.

How can I make the company total 14 appear?

public function Contador(){   
    try{
    //Sentencia SQL.
        $sql = "SELECT COUNT(id) AS codigo
                FROM nombre_tabla
                WHERE empresa_id = '14'";
        $stm = $this->pdo->prepare($sql);
        $stm->execute();
        return $stm->rowCount();
    } catch (Exception $e){
        die($e->getMessage());
    }
}
    
asked by Carlos Cespedes 06.04.2018 в 18:23
source

1 answer

2

The rowCount method of PDO returns rows affected by a DELETE statement , INSERT , or UPDATE , Then when using SELECT you are getting the number of rows returned that will always be a (according to your query) with the value of count in column codigo , if you want to get this value you can do it with fetchColumn() (without parameters, if you had more columns you should send the column number to get)

return $stm->fetchColumn(); 

Going further, if the data will be dynamic, you will need to pass this information to the query, for which it is best to prepare the sentence correctly to avoid SQL injection attacks, (possible final result)

$id = 14 ; // $valor dinámico
//Sentencia SQL.
$sql = "SELECT COUNT(id) AS codigo
                FROM nombre_tabla
                WHERE empresa_id = ? ";
$stm = $conn->prepare($sql);
//pasamos el parámetro almacenado en $id
$stm->bindParam(1, $id, PDO::PARAM_INT);
$stm->execute();
echo $stm->fetchColumn(); 
    
answered by 06.04.2018 / 18:34
source