database query returning empty array

Asked

Viewed 295 times

-3

Hello, I have an appointment function at the bank. If the query returns 1 or more rows, the function returns an object (or a class), but if the query does not return any rows, the return is:

Array
(
    [0] => 00000
    [1] => 
    [2] => 
)

The function that makes the query:

    public function selectDB($sql,$params=null,$class=null){
        $query=$this->connect()->prepare($sql);
        $query->execute($params);

        if(isset($class)){
            $rs = $query->fetchAll(PDO::FETCH_CLASS,$class) or die(print_r($query->errorInfo(), true));
        }else{
            $rs = $query->fetchAll(PDO::FETCH_OBJ) or die(print_r($query->errorInfo(), true));
        }

        return $rs;
    }

I would like some suggestion to make this function return only 0 if the query has no lines. Thanks in advance.

  • And your connection? How are you?

  • private function connect(){&#xA; try&#xA; {&#xA; $this->conexao = new PDO($this->getDBType().":host=".$this->getHost().";port=".$this->getPort().";dbname=".$this->getDB(), $this->getUser(), $this->getPassword());&#xA; }&#xA; catch (PDOException $i)&#xA; {&#xA; //se houver exceção, exibe&#xA; die("Erro: <code>" . $i->getMessage() . "</code>");&#xA; }&#xA; &#xA; return ($this->conexao);&#xA; }

1 answer

0

After a pause to breathe and think a little, I solved the problem by modifying the select function in this way:

public function selectDB($sql,$params=null,$class=null){
        $q = $this->connect();
        $stmt = $q->prepare($sql);
        $stmt->execute();
        $res = array();
        if (isset($class)) {
            foreach($stmt as $row) {
                $res[] = $this->arrayToObject($row, $class);
            }
        } else {
            foreach($stmt as $row) {
                $res[] = $row;
            }
        }
        return $res;
    }

Function arrayToObject:

private function arrayToObject(array $array, string $class_name){
        $r = new ReflectionClass($class_name);
        $object = $r->newInstanceWithoutConstructor();
        $list = $r->getProperties();
        foreach($list as $prop){
          $prop->setAccessible(true);
          if(isset($array[$prop->name]))
            $prop->setValue($object, $array[$prop->name]);
        } 
        return $object;
    }
  • 1

    Tip, use Early Returns, never use Else pq increases cyclomatic complexity...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.