Reputation: 3
How can I determine how many items there are in a while Loop?
Example:
while ($row = mysql_fetch_array($query)){
echo "<strong>name:</strong> ".$row['name']."<br>";
echo "<strong>country:</strong> ".$row['country']."<br>";
echo "<strong>house:</strong> ".$row['house']."<br>";
}
Output:
Name: Example Name
Country: Germany
House: Example street 1
House 2: Example street 3
House 3: Example street 5
I need to know this because I want to add the number behind house 2/3 as a variable. Should I place the while loop in a for loop so I can add:
$housenumber++;
echo "<strong>house ".$housenumber.":</strong> ".$row['house']."<br>";
Upvotes: 0
Views: 98
Reputation: 4411
Wrapping a loop inside a loop won't accomplish what you're getting at (or it might, but it's just needless overkill). Incrementing a variable works in any kind of loop, so you could just write:
$housenumber = 0;
while ($row = mysql_fetch_array($query)){
echo "<strong>name:</strong> ".$row['name']."<br>";
echo "<strong>country:</strong> ".$row['country']."<br>";
echo "<strong>house ".$housenumber.":</strong> ".$row['house']."<br>";
$housenumber++;
}
As Tom is saying you're using deprecated functions to retrieve MySQL data, so your code will cease to work in future versions of PHP.
Upvotes: 0
Reputation: 1068
You can use
$total = mysql_num_rows($query);
To find out the total number of rows in the while loop.
Declare this before your while loop and after $query
is defined.
However, I should point out that mysql_query
and mysql_num_rows
are deprecated and you should use MySQLi or PDO. See here for more information.
Upvotes: 3