Jump to content

Help with a WHILE() loop?


virtuexru

Recommended Posts

Ok, so I need to list these items but make them stop once its displayed 3 items. So it taps the database, lists all the results but has to stop after echoing three items. How would I go about doing this using $i as a counter?

[quote]
<?
$query  = "SELECT title, category, salary, location FROM joborder WHERE category='Development'";
$result = mysql_query($query);
$i = 0;
while(list($title,$category,$salary,$location) = mysql_fetch_row($result))
{
echo "<p/><b>$title</b>" . "<br/>$category" . " , $location" . ", $salary";
}
?>
[/quote]
Link to comment
https://forums.phpfreaks.com/topic/26383-help-with-a-while-loop/
Share on other sites

Hmm.. tried it. But now the only output I get is " ' ' ' ' " etc..

[code]
$i = 0;
while(list($title,$category,$salary,$location) = mysql_fetch_row($result) && $i <= 3)
{
$i = $i + 1;
echo "<p/><b>$title</b>" . "<br/>$category" . " , $location" . ", $salary";

}
[/code]
$i<=3 would mean 4 iterations if it begins with 0 lol

I don't know about your list method why not just use mysql_fetch_array

[code]
<?php

db_connect();
$q="SELECT * FROM table LIMIT 1";
$r=mysql_query($q);
$counter=0;
while($row=mysql_fetch_array($r)&& $counter<3)
{
echo $row['column1'].' tada! '.$row['column2'];
$counter++;
}
?>[/code]
[quote author=ralph4100 link=topic=114069.msg464105#msg464105 date=1162876172]
$i<=3 would mean 4 iterations if it begins with 0 lol

I don't know about your list method why not just use mysql_fetch_array

[code]
<?php

db_connect();
$q="SELECT * FROM table LIMIT 1";
$r=mysql_query($q);
$counter=0;
while($row=mysql_fetch_array($r)&& $counter<3)
{
echo $row['column1'].' tada! '.$row['column2'];
$counter++;
}
?>[/code]
[/quote]

Thank you for this but for some freakin' reason, the only output I get is the "tada!" part, with no errors. I know I'm putting in the right variables!

<?
  $query  = "SELECT title, category, salary, location FROM joborder (with or without LIMIT 1, still no go)";
  $result = mysql_query($query) or die (mysql_error());
  $i = 0;
  while($row=mysql_fetch_array($result) && $i<3)
  {
  echo $row['title'].' tada! '.$row['category'];
  $i++;
  }
?>
Try this

[code]
<?php

db_connect();
$q="SELECT * FROM table LIMIT 1";
$r=mysql_query($q);

while($row=mysql_fetch_array($r)&& $counter<3)
{
$i = 1;
   if ($i <= 3) {
      echo $row['column1'].' tada! '.$row['column2'];
      $i = $i +1;
   }
}
?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.