Error using PDO [closed]

1

The error is as follows:

  

Call to undefined method PDOStatement :: fecth () in /home/ubuntu/workspace/redsocial/classes/gestores/ManagerSeguidor.php on line 73 Call Stack: 0.0004 236840 1. {main} () / home / ubuntu / workspace / redsocial / index.php: 0 0.0040 322128 2.

And my function is this:

function isFollower($id, $idPerfil){
    $sql = 'SELECT count(*) FROM follow WHERE idPerfil = :idPerfil AND idFollow = :idFollow;';
    $params = array(
        'idPerfil' => $idPerfil,
        'idFollow' => $id
    );

    $res = $this->db->execute($sql, $params);
    $statement = $this->db->getStatement();

    if($res && $row = $statement->fecth()){ // EN ESTA LINEA
        return $row[0];
    }
    return 0;
}

The error is given to me in the if and I do not understand why, I have done this a thousand times, but now I can not see my error. Thanks in advance.

    
asked by Jose Antonio Lopez Lopez 06.05.2018 в 13:48
source

1 answer

1

Your main error is due to a syntax error, since the method is called fetch , not fecth .

Although I want to take this opportunity to suggest some improvements:

  • The prepare method, as indicated by the documentation, returns a PDOStatement object, to which you can apply any of the fetch methods to obtain the results. Therefore, I do not see the meaning of using the getStatement method, which seems to be a re-invention of the wheel. Usually the order is as follows:

    a. You prepare the sentence, and when preparing it, you get a reference to the object PDOStatement   b. You apply the execute to that object   c. You apply any of the fetch methods to that object.

  • PDO is a fairly complete class, its methods fetch are of a huge wealth, as to apply the most appropriate in each case. For example here, since your query returns only one column, you should use fetchColumn .

  • Seen this, your code should work like this:

    function isFollower($id, $idPerfil){
        $sql = 'SELECT count(*) FROM follow WHERE idPerfil = :idPerfil AND idFollow = :idFollow;';
        $params = array(
            'idPerfil' => $idPerfil,
            'idFollow' => $id
        );
    
        /*Mandas a preparar la sentencia, prepare devuelve un objeto PDO Statement*/
        $stmt=$this->db->prepare($sql);
        /*Usas el mismo objeto para el execute, pasándole los parámetros*/
        $stmt->execute($params);
    
        /*
          *Podemos usar una operación ternaria para evaluar $stmt
          *Si es verdadero, obtendremos el valor obtenido con COUNT
          *Si es falso, obtendremos 0
        */
        $resultado= ($stmt) ? $stmt->fetchColumn() : 0 ;
        return $resultado;
    }
    
        
    answered by 06.05.2018 / 17:12
    source