使用 mysql_fetch_field 您可以產生更強健的 mysql_fetch_assoc 版本。
當查詢 2 個具有相同欄位名稱的表格時,通常您需要使用 mysql_fetch_row 來取得以整數鍵為索引的陣列,而不是以關聯鍵為索引的陣列。這是因為第二個表格中相同名稱的欄位將覆蓋從第一個表格回傳的資料。
然而,這個簡單的函數會在索引鍵的欄位名稱前面插入表格名稱,以防止交叉覆寫。
例如:SELECT * , 'test' AS test 4 FROM table AS T_1, table AS T_2 WHERE T_1.a=T_2.b
可能會產生
mysql_fetch_assoc() 回傳
array(
'index'=>2,
'a'=>'pear',
'b'=>'apple',
'test'=>'test',
4=>4
)
mysql_fetch_table_assoc() 回傳
array(
'T_1.index' =>1,
'T_1.a'=>'apple',
'T_1.b'=>'banana',
'T_2.index'=>2,
'T_2.a'=>'pear',
'T_2.b'=>'apple',
'test'=>'test',
4=>4
)
<?php
function mysql_fetch_table_assoc($resource)
{
$data=mysql_fetch_row($resource);
if(!$data) return $data; $fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
$fields[$index]=$index;
}
else
{
$fields[$index]='';
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>