【问题标题】:double results in my array ( mysql_fetch_array )在我的数组中加倍结果( mysql_fetch_array )
【发布时间】:2020-09-28 03:17:37
【问题描述】:

好的,我执行这个

$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 jordan jordan 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 = name 等等..

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

【问题讨论】:

  • 使用mysql_fetch_array($result, MYSQL_ASSOC)。默认情况下,它返回数字和列名作为索引。我倾向于推荐mysql_fetch_assoc() 来跳过这个问题。

标签: php mysql


【解决方案1】:

来自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

【讨论】:

  • 谢谢。我是 php 新手(1-2 天前开始)。再次感谢您的快速答复
  • 从 mysql_fetch_array 更改为 mysql_fetch_row 解决了我的加倍问题 ($row=mysql_fetch_row($query))
猜你喜欢
  • 2015-02-20
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多