简体   繁体   中英

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 instead 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM