我对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."
}
}为什么它有重复的元素?我检查了数据库,它是正常的。有人能解释一下我错过了什么吗?
发布于 2015-10-18 10:56:04
您可以将第二个参数传递给mysql_fetch_array函数,以告诉它是返回关联数组(列到行值的散列映射)还是返回行元素的常规数组。默认情况下,它将同时返回两者。
http://php.net/manual/en/function.mysql-fetch-array.php
还有一些专用函数可以将行值作为数组和哈希表获取: mysql_fetch_row() mysql_fetch_assoc()
发布于 2015-10-18 10:56:58
这是因为在默认情况下,mysql_fetch_array同时返回数值数组和关联数组。检查php手动mysql_fetch_array
请尝试使用mysql_fetch_assoc而不是mysql_fetch_array,因为mysql_fetch_array在PHP5.5.0中已被弃用,并在PHP7.0.0中被删除。
但是如果你还想用这个的话,这个会有帮助的。
尝试传递第二个参数mysql_fetch_array($result, MYSQL_ASSOC)或mysql_fetch_array($result, MYSQL_NUM)
https://stackoverflow.com/questions/33193780
复制相似问题