i hope to iterate the elements fetched from datebase
But the result looks very unexpected .
I found the code below print the $value
and echo "<td id=".$key.$tag.">".$value."</td>";
twice. Is there anything i misunderstood?
function selectTable($table){
$sql= "SELECT * FROM ".$table ;
$result=mysql_query($sql)
or die(mysql_error());
return $result;
}
$table = 'battery_con';
$result = selectTable($table);
unset($table);
while($row = mysql_fetch_array($result)){
......
foreach ($row as $key => $value) {
print $value;
echo "<td id=".$key.$tag.">".$value."</td>";
}
.....
}
You are using mysql_fetch_array which by default returns an array with two elements per column (this is what the second (optional) paramter means: result_type = MYSQL_BOTH
).
One is indexed with an integer representing the column index, one is indexed with the column name.
That's why you get two entries in your list. You would set the second parameter to MYSQL_ASSOC
to get just one value per column.
Please use mysql_fetch_assoc()
place of mysql_fetch_array()
I hope it will help
In addition to @Andreas's answer by default mysql_fetch_array
gives both associative and numeric indexes, if you don't want this you can limit it with the second parameter in your while loop:
$row = mysql_fetch_array($result, MYSQL_NUM); // numeric keys only
$row = mysql_fetch_array($result, MYSQL_ASSOC); // associative keys only
As previously mentioned by @sonusindhu you can also use mysql_fetch_row
to only get numeric keys, or mysql_fetch_assoc
to only get associative keys.
Update
The mysql_xxx() functions being deprecated you should consider using the mysqli_xxx() functions instead.
See the example 1 of the php manual for more details: http://php.net/manual/en/mysqli-result.fetch-array.php