Performance of fetching DB items individually vs looping with php -
out of curiosity, of these segments of code have faster performance time when implemented on mass scale?
let's have table members , want fetch photos.
method 1
$members = $db->query('select * members order id asc'); foreach($members $m) $memberids[] = $m['id']; $photos = $db->query('select * photos member in'.join(',', $memberids).' order id asc'); foreach($photos $p) { // multi_arr_search(search_val, search_column, search_array) returns parent key in multi dimensional array $memberarraykey = multi_arr_search($p['member'], 'id', $members); $members[$memberarraykey]['photos'][] = $p; }
or
method 2
$members = $db->query('select * members order id asc'); foreach($members $k=>$m) $members[$k]['photos'] = $db->query('select * photos member='.$m['id'].' order id asc');
method 1 result in fewer queries being ran, requires more php work.
neither. using 15 years old deprecated methods. if want go fast, need pdo prepared statements. @alberto right. pretty sure, can have 1 , sql perform here way might want consider in case off:
$showerror = true; define("sqlhost", "127.0.0.1"); define("sqluser", "login"); define("sqlpass", "password"); define("sqlsgbd", "database"); $conn = new pdo('mysql:host=' . sqlhost . ';dbname=' . sqlsgbd . ';charset=utf8', sqluser, sqlpass); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql1 = 'select * members order id asc'; $stmt1 = $conn->prepare($sql1); $sql2 = 'select * photos member in ? order id asc'; $stmt2 = $conn->prepare($sql2); try { $stmt1->execute(); $members = $stmt1->fetchall(pdo::fetch_assoc); } catch (pdoexception $e) { if ($showerror === true) { var_dump("error query 1:" . __line__ . "-------" . __function__ . "-------" . $e->getmessage()); exit; } } if (count($members) !== 0) { $memberids = array(); foreach ($members $m) { $memberids[] = $m['id']; } $memberlist = join(',', $memberids); foreach ($members $memberarraykey => $result1) { $stmt2->bindparam(1, $memberlist, pdo::param_str); try { $stmt2->execute(); $photos = $stmt2->fetchall(pdo::fetch_assoc); } catch (pdoexception $e) { if ($showerror === true) { var_dump("error query 2:" . __line__ . "-------" . __function__ . "-------" . $e->getmessage()); exit; } } if (count($photos) !== 0) { $memberarraykey = multi_arr_search($p['member'], 'id', $members); $members[$memberarraykey]['photos'][] = $p; } } }