2012-03-04 61 views
3

好吧,我執行這個雙重結果

$table = get_personel_table(1); 
function get_personel_table($id) 
    { 
     global $connection; 
     $query = "SELECT * "; 
     $query .= "FROM employees "; 
     $query .= "WHERE id=" . $id . " "; 
     $query .= "ORDER BY id ASC"; 
     $query_result = mysql_query($query , $connection); 
     confirm_query($query_result); 
     $query_result_array = mysql_fetch_array($query_result); 
     return $query_result_array; // returns associative array!; 
    } 

而且我的foreach

foreach($table as $table_var) 
{ 
    echo "<td>" . $table_var . "</td>"; 
} 

,並通過這樣做,我得到的雙輸出...「1 1 1 1喬丹約旦9108121544 9108121544 testemail子testemail子testAddress testAddress testCounty testCounty」

這下面是print_r的結果

Array 
    (
     [0] => 1 
     [id] => 1 
     [1] => 1 
     [department_id] => 1 
     [2] => jordan 
     [name] => jordan 
     [3] => 9108121544 
     [EGN] => 9108121544 
     [4] => testEmail 
     [email] => testEmail 
     [5] => testAddress 
     [address] => testAddress 
     [6] => testCounty 
     [country] => testCounty 
    ) 

我在數據庫中的信息是id => 1,department_id => 1,依此類推...我的問題是爲什麼我得到雙重反饋(我不知道如何調用它), 0 = id,1 = department_id,2 =名稱等。

當我做foreach(...)我得到的一切都翻了一番。

+3

使用'mysql_fetch_array($ result,MYSQL_ASSOC)'。默認情況下,它將數字和列名作爲索引返回。我傾向於推薦'mysql_fetch_assoc()'來避免這個問題。 – 2012-03-04 16:51:45

+1

可能重複的[mysql_fetch_array和只有字符串數組鍵](http://stackoverflow.com/questions/7440479/mysql-fetch-array-and-only-string-array-keys) – 2012-03-04 16:52:57

回答

14

the manual

mysql_fetch_array - 從結果集中取得一行作爲關聯陣列,數字數組,或兩者

默認情況下,mysql_fetch_array給出兩者締合和數字索引。你不想要這個。你可以用第二個參數限制它:

$query_result_array = mysql_fetch_array($query_result, MYSQL_NUM); // numeric keys only 
$query_result_array = mysql_fetch_array($query_result, MYSQL_ASSOC); // associative keys only 

您還可以使用mysql_fetch_row只得到數字鍵,或mysql_fetch_assoc只得到關聯鍵。

$query_result_array = mysql_fetch_row($query_result); // numeric keys only 
$query_result_array = mysql_fetch_assoc($query_result); // associative keys only 
+0

謝謝。我是PHP的新手(1-2天前開始)。並再次感謝您的快速回答 – Jordashiro 2012-03-04 16:52:24

+0

從mysql_fetch_array更改爲mysql_fetch_row解決了我的一倍($ row = mysql_fetch_row($ query)) – zzapper 2017-11-08 10:52:19