2012-03-04 63 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