2013-04-20 71 views
0

我有一個簡單的用戶列表:用戶名,密碼,電子郵件,姓名,出生日期,地址和城市。前三個是強制性的,但其餘的可以爲空。 我正在連接到數據庫並獲取數組中的行並將其打印。爲什麼從數據庫檢索數據被添加到php數組兩次?

$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] => [email protected] [email] => [email protected] [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] => [email protected] [email] => [email protected] [3] => Barış [name] => Barış [4] => [surname] => [5] => 0000-00-00 [birthdate] => 0000-00-00 [6] => [address] => [7] => [city] =>) 

問題是爲什麼有兩個[0] =>巴里斯和[用戶名] =>巴里斯。我期待只有用戶名=> baris。我錯了嗎?我在哪裏失蹤? 如果我解決了這個問題,我會通過刪除註釋將數組轉換爲json。

+0

嘗試'print'或'echo'而不是'print_r' – imulsion 2013-04-20 12:25:31

+0

它給我一個錯誤。 – 2013-04-20 12:27:13

+0

在手冊中對其預期的行爲進行了細緻的解釋。 – Nanne 2013-04-20 12:35:35

回答

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

+0

謝謝,我應該先看看文檔。我的錯。 – 2013-04-20 12:43:48

+0

不客氣...... :) – 2013-04-20 12:47:50

1

,如果你只需要username => baris

嘗試mysqli_fetch_assoc

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

它返回表示在結果集,其中陣列中的每個鍵表示的結果集的的 一個名稱中提取行 串的關聯數組如果 結果集中沒有更多行,則爲NULL或NULL。

1

我想你正在尋找的是與resultType參數。看看這個頁面:mysqli_result::fetch_array

你可能要調用的函數fetch_array像這樣:

mysqli_fetch_array($data, MYSQLI_ASSOC) 
0

嘗試使用的mysqli_fetch_assoc()代替mysqli_fetch_array()

mysqli_fetch_array()作爲枚舉和關聯獲取數據,所以如果你只需要關聯數組使用mysqli_fetch_array()

如果你想知道更多關於它的事情,你也可以read the documentation