使用 php 从几个 mysql 表中检索数据的最佳方法
需要从几个表中获取数据 -表一包含所有产品详细信息和product_id -表二有额外的细节,与product_id相关
,从所有表获取数据的最佳方法是什么,也许将它们存储在同一个数组中,或者最好是单独的数组,但长度相同,
从表1获取数据
$result = mysql_query("SELECT product_id,model,name,barcode FROM product");
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
如果我使用应该 我只是循环遍历 data[$i]['product_id'] 并再次查询并存储在新数组中? 例如
$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'];
}
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'];
}
最好的方法是让数据库处理一个大查询,而不是执行大量不同的查询(每个产品一个):
将其提取到数组中,就像您正在做的那样,就可以了。
The best way would be to let the database handle one big query, instead of performing lots of different queries (one per product):
Fetch that into an array as you are doing, and you are fine.