Im creating a function that cycles through all the rows of a MySQL database, then populates a bunch of anchor tags with specific data pertaining to the then current id Its on. My problem is that it will only populate the first tag with the information, and no others after it according to what row it should be on. The code will hopefully better explain this.
public function getLinks() {
$output = "";
$data = $this->_db->get('SELECT *', 'shutins', array('id', '>', 0));
echo $data->count(); // Currently returns 2
for($i = 1; $i < ($data->count() + 1); $i++) { // Set the count to 3 to make sure it should continue
$this->find($i); // Gets the first row only
$output .= "<a href=\"shutin.php?id={$this->data()->id}\" class=\"link\"><span>{$this->getName()}</span> <img class=\"next\" src=\"img/next.png\" width=\"20\"/></a>";
$i++; // Doesn't seem to increment then start again
}
return $output;
}
If you need to see more of my code files, Im happy to provide them.
You are double incrementing your $i
variable. The third "parameter" of a for loop is statements to execute after each iteration. Your first loop will have $i
as 1, then when it starts the second iteration $i
will be three. It will check your condition ($i < ($data->count() + 1)
) which will be false and the loop will end.
Side note; the second "parameter" of the loop is for statements to be run (and checked) at the beginning of each iteration. A more efficient way of writing the loop will be:
for($i = 1, $count = $data->count() + 1; $i < $count; $i++) {
This is because the count and addition performed to populate the $count
variable only happens once, not for every iteration in the loop.
You are incrementing the $i
variable two times in the loop. Remove the $i++; // Doesn't seem to increment then start again
from your loop
for($i = 1; $i <= $data->count(); $i++) { // You can use "<=" instead of ($data->count() + 1) to make it simple
$this->find($i); // Gets the first row only
$output .= "<a href=\"shutin.php?id={$this->data()->id}\" class=\"link\"><span>{$this->getName()}</span> <img class=\"next\" src=\"img/next.png\" width=\"20\"/></a>";
}