php - Am i being very inefficient ? mysqli call in loop -


i have database 2 tables, have primary key(item_id) , foreign key(color_id) in items table. list items out color title below,

item details

//item_id

//color_id

//details

colors

//color_id

//color_suffix

//color_details

i list these items out color suffix(re) item details item details item details etc etc...

color suffix(rt) item details item details

to loop through colors table , make sql call each time loops

$query = "select * colors"; $result = mysqli_query($connection,$query); while($data= fetch_array($result)){     echo "<h2>{$data['color_suffix']}</h2>";     $query2 = "select ... items color_id = {$data['color_id']}";     $result2 = mysqli_query($connection,$query);     while($item = fetch_array($result2)) {         //list items     } } 

this kind of sudo code im wondering if there more efficient way. i've been reading on sql inner join, method should use ?

i've read on prepared statements, ill honest not understand syntax on either.

should doing ? or extremely inefficient ? bear in mind there around 30 different colors 10 - 50 items each lot of sql calls.

could provide basic sudo code me understand how achieve ?

thank in advance ryan

use joins. add little logic groupings.

 $query = "select ... colors, items items.color_id = colors.color_id order colors.color_id";  $stmnt = $db->prepare($query);  $stmnt->bind_results($color_id, $color_suffix, ...);  $stmnt->execute();  $cur_col_id = '';  while($stmnt->fetch())  {    if($color_id !== $cur_col_id)    {      echo '<h2>' . $color_suffix . '</h2>';      $cur_col_id = $color_id;    }    //print items here, no second loop.  } 

keep in mind ... shouldn't *, should list of actual fields using. order has match in bind_results call. should add error checking , handling.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -