2015-10-18 125 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)