Jump to content

Looping Names


mch987

Recommended Posts

trying to write a code that will repeat a name until it gets to the number on the database.

Database Information

Name Number

Mike 2

Oscar 2

Robert 1

 

Wanted to look like

Full Name

Mike

Mike

Oscar

Oscar

Robert

 

 

Here is my Code

<?php
$result = mysql_query("SELECT * FROM `people`");
echo
"<table border='1'>
<tr>
<th>Full Name</th>
<th> </th>
</tr>";
for ($i = 1 , $row = mysql_fetch_array($result) ; $i <= $row['Number'] ; $i++ )
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
?>

When i run the code it will only show the result like this

Full Name

Mike

Mike

 

and when i put the "for" again in the bottom of the first one it will show like this

Full Name

Mike

Mike

Oscar

Oscar

 

 

<?php
$result = mysql_query("SELECT * FROM `people`");
echo
"<table border='1'>
<tr>
<th>Full Name</th>
<th> </th>
</tr>";
for ($i = 1 , $row = mysql_fetch_array($result) ; $i <= $row['Number'] ; $i++ )
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";

echo "<td> </td>";
echo "</tr>";
}
for ($i = 1 , $row = mysql_fetch_array($result) ; $i <= $row['Number'] ; $i++ )
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";


echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
?>

 

 

i need something to repeat "For" until it finishes all the Names

Link to comment
Share on other sites

how about

while($row = mysql_fetch_assoc($result)){
$num = $row['Number'];
if($num > 1){
for($i=0;$i<$num;$i++){
echo $row['name'];
}
}
else{
echo $row['name'];
}
}

you'll need to add in your own formatting, and the code is untested - but while loops are the standard (with refference to usage) way of looping through database results.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.