为什么从数据库中检索到的数据被添加到php数组两次


Why data retrieved from database was added to php array two times?

我有一个简单的用户表,包含用户名、密码、电子邮件、姓名、姓氏、出生日期、地址和城市。前三个是强制性的,但其余的可以为空。我正在连接到数据库并在数组中获取行并打印它。

$dbc=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$sql = "select * from user"; 
$data = mysqli_query($dbc, $sql) or die("query exec error");
//$json = array();
if(mysqli_num_rows($data)){
    while($row=mysqli_fetch_array($data)){
        //$json['Kullanici'][]=$row;
        print_r($row);
        echo "<br /><br />";
    }
}
mysqli_close($dbc);
//echo json_encode($json);

但是输出是这样的:

Array ( [0] => ayse [username] => ayse [1] => b1b3773a05c0ed0176787a4f1574ff0075f7521e [password] => b1b3773a05c0ed0176787a4f1574ff0075f7521e [2] => ayse@hotmail.com [email] => ayse@hotmail.com [3] => [name] => [4] => [surname] => [5] => 0000-00-00 [birthdate] => 0000-00-00 [6] => [address] => [7] => istanbul [city] => istanbul )
Array ( [0] => baris [username] => baris [1] => 7c4a8d09ca3762af61e59520943dc26494f8941b [password] => 7c4a8d09ca3762af61e59520943dc26494f8941b [2] => bakkurt@hotmail.com [email] => bakkurt@hotmail.com [3] => Barış [name] => Barış [4] => [surname] => [5] => 0000-00-00 [birthdate] => 0000-00-00 [6] => [address] => [7] => [city] => ) 

问题是为什么同时存在[0]=>baris和[username] =>baris。我只期待用户名=>baris。我错了吗?我错过了什么?如果我解决了这个问题,我将通过删除注释将数组转换为json。

这不是问题,如果你查看mysqli_fetch_array()函数的PHP文档,它接受一个参数resulttype;它决定是否将记录作为单独具有数字索引的数组返回,单独具有关联索引还是两者都返回(这是您所拥有的)。
缺省使用MYSQLI_BOTH
单独获取数字索引:

while($row=mysqli_fetch_array($data, MYSQLI_NUM)){
    //this will always return with numeric indices alone
}
PHP mysqli_fetch_array

如果只需要username => baris

<尝试strong> mysqli_fetch_assoc 。

礼貌 - http://www.php.net

返回一个字符串的关联数组,该数组表示所获取的行在结果集中,其中数组中的每个键表示的名称结果集的列之一,如果没有更多的行,则为NULLresultset。

我认为你正在寻找的是resulttype参数。看一下这个页面:mysqli_result::fetch_array

你可能想这样调用fetch_array函数:

mysqli_fetch_array($data, MYSQLI_ASSOC)

试着用mysqli_fetch_assoc()代替mysqli_fetch_array()

mysqli_fetch_array()获取的数据既可以是枚举的,也可以是关联的,所以如果你只需要关联数组,就使用mysqli_fetch_array()

如果你想了解更多的信息,你也可以阅读文档