Retrieving data from the database
Please give me a hand retrieving data from the database and showing it.
I'm learning and this is holding me from advancing :(
I have:
$result = mysql_query($sql);
$num_reg = mysql_num_rows($result);
echo $num_reg; // this shows 3
while($row = mysql_fetch_assoc($result))
{
foreach($row as $value)
{
//Now I need to operate with the rows values.
echo $row['PHONE'];
But this i开发者_运维知识库nstead of printing the phone numbers, prints them 5 times each
What am I doing wrong?
Thanks a lot
Remove foreach
loop
while($row = mysql_fetch_assoc($result))
{
echo $row['PHONE'];
echo $row['NAME'];
echo $row['OTHER_FIELD'];
}
you don't need foreach in that case
while($row = mysql_fetch_assoc($result))
{
echo $row['PHONE'];
}
Probably your $row
has 2 elements, and inside foreach
your echo $row['PHONE']
is called once for every element
do a print_r($row) in your while loop and a print_r($value) in your foreach loop. Then ask you why do you echo $row in a loop on $row elements.
You don't need a second foreach() loop inside the while() loop to work on the values. What you're doing here is looping through the rows then looping through the values but if you already have access to the values via the $row variable you don't need to loop again. The fact you get the phone number 5 times suggests you have 5 columns in your table.
An example - remove the foreach() loop:
while($row = mysql_fetch_assoc($result)){
echo $row['PHONE'];
echo $row['NAME'];
echo "<br />";
}
I'm guessing you have a variable called "name" but if not just swap it for one you do have. The last echo just prints a new line to make it easier to read.
精彩评论