我是PHP和MySQL的新手,我正在尝试从MySQL表中获取数据并进行打印。我打电话给数据库,效果很好。我能够阅读信息。出。但是数据中有重复数据。 到目前为止,我有:
<?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) "test@test.com"
["email"]=>
string(13) "test@test.com"
[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 :(得分:0)
您可以将第二个参数传递给mysql_fetch_array函数,告诉它是否返回关联数组(hashmap - 列到行值)或常规行元素数组。默认情况下,它将返回两者。
http://php.net/manual/en/function.mysql-fetch-array.php
还有专用函数将行值作为数组和hashmap获取: 和mysql_fetch_row() mysql_fetch_assoc()
答案 1 :(得分:0)
这是因为mysql_fetch_array
默认返回数字和关联数组,请查看php manual mysql_fetch_array
请尝试使用mysql_fetch_assoc
而不是mysql_fetch_array
,因为在PHP 5.5.0中已弃用mysql_fetch_array
,并且已在PHP 7.0.0中删除它。
但如果您仍想使用此功能,那么
尝试传递第二个参数mysql_fetch_array($result, MYSQL_ASSOC)
或mysql_fetch_array($result, MYSQL_NUM)