tags:

views:

44

answers:

4

Given a $result from a SELECT query that returned 20 rows, what is the simplest way to accomplish what the comment sugggests in the loop?

while ($row = mysql_fetch_assoc($result))
{
    // echo "success" when i get to the 9th row
}
+1  A: 
$i=0;

while ($row = mysql_fetch_assoc($result))
{
    ++$i;
    if($i==9)
        echo "success";
}
Blindy
Is there anyway to do it without dealing with $i? No way to access the location within $result?
Matthew
Missing the $ before the i var as well as you increment the counter before the check so array index zero will be skipped
Phill Pafford
I'm assuming his "9'th row" is 1-based, so I'm counting starting from 1. You're right about $ tho, my php is rusty.
Blindy
A: 
$i = 0; // Or 1 if need be
while ($row = mysql_fetch_assoc($result))
{
    // echo "success" when i get to the 9th row
   if($i == 9) {
      echo "success";
   }
   $i++;
}

or

while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
  if($row[8] != '') {
   echo "success"; 
  }
}

or

while ($row = mysql_fetch_assoc($result))
{
  if($row['column_name_of_the_ninth_field'] != '') {
   echo "success"; 
  }
}
Phill Pafford
The second example would reference 8 in the $row, not the $result
Matthew
Fixed, Should access the 9th array index now
Phill Pafford
I think you misunderstood the question
Matthew
How? $row is an array element(which starts at zero for the first field) and I have shown three different ways to access the 9th element and echo success. What didn't I understand?
Phill Pafford
I think you are confusing rows and columns
Tom Haigh
+1  A: 

You can use mysql_data_seek() to check if the 9th row exists:

if(mysql_data_seek($result, 8) !== false) {
    // success, internal pointer is now at 9
    // still need to call mysql_fetch to get the row
}

but you can't get at the internal pointer short of counting yourself. Using a for loop keeps it a bit tidier:

for($i = 0; $row = mysql_fetch_assoc($result); $i++) {
    if($i == 8) // success
}
rojoca
Thanks. I knew $i++ was one way to do it, I was just hoping there was a cleaner way.
Matthew
A: 

the methods detailed already in the other answers are all valid ways to do it.

if what you're really looking to do is to move the internal pointer to the 9th result without having to go through a loop, then this is what you may be looking for:

if ( mysql_data_seek ($result,9) ) echo "success";
pxl