NotionCommotion Posted September 13, 2017 Share Posted September 13, 2017 (edited) 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 September 13, 2017 by NotionCommotion Quote Link to comment Share on other sites More sharing options...
requinix Posted September 13, 2017 Share Posted September 13, 2017 Provided each MyClass has the exact same connection (probably do) then it should be fine: same query every time and there's no benefit to having instances use their own prepared statement. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.