Baldráni Baldráni - 5 months ago 6
SQL Question

How to add condition in query()?

So this must be a newbie question but i'm basically there in php and I'm stuck at this point.

I'm executing queries like that :

$db->query($query);


And this is the function query() :

public function query($statement){
$req = $this->getPDO()->query($statement);
$datas = $req->fetchAll(PDO::FETCH_OBJ);
return $datas;
}


So this is working as long as the output of my query is an object.

But let say I want to update or delete a row. How can I say that I want a condition on this function ?
Is there a parameters for the type of the query output ?

Edit :



Since this seems to not be clear in this precise function I can't use queries like
UPDATE ...
or
DELETE..
due to the fact that it is outputting nothing.
This is precisely what I want to do something like

public function query($statement){
if(output is an object){
$req = $this->getPDO()->query($statement);
$datas = $req->fetchAll(PDO::FETCH_OBJ);
return $datas;
} else if (there is no output) {
$sth = $dbh->prepare($statement));
$sth->execute();
}
}

Answer

You can check if the $statement starts with the operation Keyword: insert, update, select ...

public function query($statement){
     $req = $this->getPDO()->query($statement);
    if(substr( $statement, 0, 6 )) === "SELECT"){      
       $datas = $req->fetchAll(PDO::FETCH_OBJ);
    }elseif(substr( $statement, 0, 6 )) === "UPDATE"){
    ....
    }

    return $datas;
}
Comments