2015-10-18 127 views
0

我對PHP和MySQL非常陌生,正試圖從MySQL表中獲取數據並打印它。我打電話給數據庫,它很好。我可以閱讀信息。出。但數據中有重複。 到目前爲止,我有:MySQL和PHP重複打印

<?php 
/// Make a MySQL Connection 
mysql_connect("localhost", "loop", "XXX") or die(mysql_error()); 
mysql_select_db("loop") or die(mysql_error()); 

// Retrieve all the data from the "profile" table 
$result = mysql_query("SELECT * FROM profile") 
or die(mysql_error()); 

//print out info. 
while ($row = mysql_fetch_array($result)) { 
    echo("<pre>"); 
    var_dump($row); 
    echo("</pre>"); 
} 
?> 

這將產生:

array(1) { 
    [0]=> 
    array(14) { 
    [0]=> 
    string(1) "1" 
    ["id"]=> 
    string(1) "1" 
    [1]=> 
    string(13) "[email protected]" 
    ["email"]=> 
    string(13) "[email protected]" 
    [2]=> 
    string(8) "passcode" 
    ["pass"]=> 
    string(8) "passcode" 
    [3]=> 
    string(4) "John" 
    ["nameFirst"]=> 
    string(4) "John" 
    [4]=> 
    string(5) "Smith" 
    ["nameLast"]=> 
    string(5) "Smith" 
    [5]=> 
    string(8) "face.jpg" 
    ["pic"]=> 
    string(8) "face.jpg" 
    [6]=> 
    string(16) "Some dummy text." 
    ["bio"]=> 
    string(16) "Some dummy text." 
    } 
} 

爲什麼它有重複的元素呢?我檢查了數據庫,它是確定的。有人可以解釋我缺少的東西嗎?

+0

考慮使用新的方法,如mysqli的..答案是從PHP文檔以下:要獲取的數組的類型。它是一個常量,可以取下列值:MYSQL_ASSOC,MYSQL_NUM和MYSQL_BOTH。 MYSQL_BOTH是默認值。 – user993553

回答

0

您可以將第二個參數傳遞給mysql_fetch_array函數,告訴它是否返回一個關聯數組(hashmap - 列值到行值)或常量數組的行元素。默認情況下它將返回兩者。

http://php.net/manual/en/function.mysql-fetch-array.php

還有一些專用功能,以抓取行值作爲數組和HashMap: mysql_fetch_row()能夠 mysql_fetch_assoc()

0

這是因爲mysql_fetch_array返回數值和關聯數組默認檢查PHP手動mysql_fetch_array

請儘量使用mysql_fetch_assoc而不是mysql_fetch_array因爲mysql_fetch_array是PHP 5.5.0過時,它爲r在PHP 7.0.0中發揮作用。

,但如果你仍然想使用這個比這將有助於

試圖通過第二個參數mysql_fetch_array($result, MYSQL_ASSOC)mysql_fetch_array($result, MYSQL_NUM)