I am very new to PHP and MySQL and am trying to get data from a MySQL table and print it. I make a call to the database and it works great. I am able to read info. out. but there are duplicates in the data. So far I have:
<?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>");
}
?>
This produces:
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."
}
}
Why does it have duplicate elements? I checked the database and it is OK. Can someone explain what I am missing?
You can pass a second parameter to mysql_fetch_array function to tell it whether to return an associative array (hashmap - of columns to row values) or a regular array of row elements. By default it will return both.
http://php.net/manual/en/function.mysql-fetch-array.php
There are also dedicated functions to fetch row values as an array and hashmap: mysql_fetch_row() mysql_fetch_assoc()
This is because mysql_fetch_array
returns both numeric and associative array by default check php manual mysql_fetch_array
Please try to use mysql_fetch_assoc
instead of mysql_fetch_array
because mysql_fetch_array
was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
but if you still want to use this than this will help
try to pass a second parameter mysql_fetch_array($result, MYSQL_ASSOC)
or mysql_fetch_array($result, MYSQL_NUM)