0

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

$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。

4

4 回答 4

2

这不是问题,如果您查看该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

于 2013-04-20T12:33:06.267 回答
1

如果你只需要username => baris

尝试mysqli_fetch_assoc

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

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

于 2013-04-20T12:32:50.017 回答
1

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

您可能想像这样调用 fetch_array 函数:

mysqli_fetch_array($data, MYSQLI_ASSOC)
于 2013-04-20T12:34:27.857 回答
0

尝试使用mysqli_fetch_assoc()而不是mysqli_fetch_array().

mysqli_fetch_array()以枚举和关联方式获取数据,因此如果您只需要关联数组,请使用mysqli_fetch_array().

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

于 2013-04-20T12:34:30.097 回答