I want to know what is the best way to get several records of a mysql database, I leave a simple example of my situation. I have a static method that queries a database and converts the result into an object that I have defined.
class Persona {
public $id;
public $nombre;
function __construct($id,$name){
$this->id = $id;
$this->nombre = $name;
}
public static function getPersona($personid){
$db = new ConnectionDB();
$stmt = $db->prepare("SELECT * FROM Persona WHERE id = ?");
$stmt->bind_param('i',$personid);
$stmt->execute();
$stmt->bind_result($id,$name);
$stmt->fetch();
return new Persona($id,$name);
}
}
Which option would have better performance?
Option 1: Create a method that receives several ids and check them one by one using the previous method
public static function getPersonas($ids){
$personas = array();
foreach($ids as $id){
$personas[] = new getPersona($id);
}
return $personas;
}
Option 2: Create a method that uses IN in the query.
public static function getPersonas($ids){
$db = new ConnectionDB();
$sql = "SELECT * FROM personas WHERE id IN (" . implode(',',$ids) .")";
$persons = array();
if($result = $db->query($sql)){
while($row = $result->fetch_assoc()){
$persons[] = $row;
}
}
$oPersons = array();
foreach($persons as $p){
$oPersons[] = new Persona($p['id'],$p['name']);
}
return $oPersons;
}