Quick question. Whilst using the prepare method in mysqli. It is possible/a good idea; to use it twice within the same mysqli connection? Example:
OOP layered
public function getStuff(){
$posts=array();
$query = $this->DBH->prepare('SELECT * FROM table WHERE stuff =?');
$query->bind_param('s','param');
$query->execute();
$query->bind_result($ID,$col1,$col2,$etc);
while($query->fetch()){
$posts[]=array('ID'=>$ID,'col1'=>$col1,'extras'=>$this->getExtras($ID));
}
$query->close();
return $posts;
}
private function getExtra($postID){
$extras=array();
$query = $this->DBH->prepare('SELECT * FROM anotherTable WHERE moreStuff =?');
$query->bind_param('s',$postID);
$query->execute();
$query->bind_result($ID,$col1,$col2,$etc);
while($query->fetch()){
$extras[]=array('ID'=>$ID,'col1'=>$col1,'etc'=>$etc);
}
$query->close();
return $extras;
}
Right my possible error is that I’ve used the same variable and the same database connection. I’m not 100% sure this will work as I’ve called $this->DBH whilst it is already being used in the parent function. Is there a better method to what I’m trying to achieve or is there a better structure I can use. Or should I just give up and use a separate variable? lol
Hopeful outcome:
$posts=array('ID'=>'column ID number','col1'=>'column1 data', 'extras'=>array('ID'=>'second table\'s ID number','col1'=>'second tables data','etc'=>'etc etc etc'));
In your example above, the variables which matter are
$query. Each of those is local to its own method, and so the variables themselves will not collide. The MySQLi connection$this->DBHis capable of handling multiple open statements at once if circumstances are right.The place where you need to use caution is with their execution order. If you prepare and execute a statement but do not fetch all rows from it, you may not be able to
prepare()the next one until all rows have been fetched unless you first close it withmysqli_stmt::close()to deallocate the open statement handle.For example:
Edit: misread your example…
Looking at your example above, you are indeed calling
getExtras()while you are fetching from thegetStuff()statement. You may run into the issue described above. Your two operations in this case may be able to be handled with a singleJOINinstead, from which you fetch in only one loop to populate all your variables and build your output array as you want it. Depending on your need, this should either be anINNER JOINif a related row is expected to exist in theothertable, or aLEFT JOINif the relatedothertablemay or may not have a row that matches the given ID.