phpmysqlarraysassociate

best way to retrieve data from few mysql tables with php


Need to fetch data from a few tables -table one has all product details and the product_id -table two has extra details, associated with the product_id

what is the best way to get data from all tables and perhaps store them in the same array, or at best separate arrays but of same length

if i get the data from table 1 using

 $result = mysql_query("SELECT product_id,model,name,barcode FROM product");  
 $data = array();
 while($row = mysql_fetch_assoc($result))
 {
  $data[] = $row;
 }

should i just loop through data[$i]['product_id'] and query again and store in a new array? e.g

   $data2 = array();

   for($j=0; $j<=$count; $j++){
    $id = $data[$j]['product_id'];
    $result2 = mysql_query('SELECT stuff FROM product_descp WHERE product_id = $id');
    $row2 = mysql_fetch_array($result2);
    $data2[] = $row2['stuff'];
   }

Solution

  • The best way would be to let the database handle one big query, instead of performing lots of different queries (one per product):

    SELECT product_id,model,name,barcode 
    FROM product 
    JOIN product_descp 
    ON product.product_id = product_descp.product_id
    

    Fetch that into an array as you are doing, and you are fine.