Jump to content

Prepared statement in a function


NotionCommotion

Recommended Posts

I will be performing a query multiple times and for readability and/or code reduction wish to perform the query in a function.

 

Anything wrong with the following?  Originally, I was thinking of saving the prepared statement in $this->stmt, but then multiple instances of  MyClass would have their own prepared statement which doesn't seem like a big deal but I see no reason why necessary.  Any more recommended way to do so?

 

Thanks

class MyClass
{
    public function getSomeData($id)
    {
        static $stmt;
        if(!$stmt) $stmt=$this->db->prepare('SELECT a,b,c from t WHERE id=?');
        $stmt->execute($id);
        $rs=[];
        while($record = $stmt->fetch()) {
            //manipulate data as necessary
            $rs[]=$record;
        }
        return $rs;
    }
}

 

EDIT.  I know this won't work as is (trying to get it before the edit time expires!), but is something like this possible where the second function returns one result at a time? EDIT 2.  Guess I should just use return fetchAll();

 

class MyClass
{
    public function other($id)
    {
        while($record = $this->getSomeData($id) {
            //manipulate data as necessary
            $rs[]=$record;
        }
        return $rs;
    }


    private function getSomeData($id)
    {
        static $stmt;
        if(!$stmt) $stmt=$this->db->prepare('SELECT a,b,c from t WHERE id=?');
        $stmt->execute($id);
        return $stmt->fetch();
    }
}
Edited by NotionCommotion
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.