This question already has an answer here:
I coded a simple function to loop trough and display all variables in the sql table. However foreach $row displays the rows two times, 1 time as a row name and 1 time as a row number.
1 : $row['NAME'] Name form
2 : $row[0]' Number form
PHP :
<?php
include "condetails.php";
$query = "select * from pagedetails";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
foreach($row as $var => $val) {
echo "VARNAAM :".$var;
echo "<br />";
echo "VALUE".$val;
echo "<br />";
echo "<br />";
}
}
?>
OUTPUT :
VARNAAM :0 VALUE1
VARNAAM :id VALUE1
VARNAAM :1 VALUEdddd
VARNAAM :h1txt VALUEdddd
</div>
It's displayed twice because mysql_fetch_array()
grabs the column name and its number.
If you want just the column names try using mysql_fetch_assoc()
, keep in mind mysql_* functions are depreciated and you should be using PDO / MySQLi :)
mysql_fetch_array returns a mixed array with keys as numbers and as column names. You probably want mysql_fetch_assoc(), which only returns the name keys.
From the manual:
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
What you you're really looking for is mysqli_fetch_assoc()
:
Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.