5

I have the following code that fetches a single row:

$query = "SELECT *
          FROM translations
          WHERE iddoc = '$id'
          AND submitted = 1;";
$result = mysqli_query($query);
$row = mysqli_fetch_array($result);

I know this is useful in a while loop, where you can just loop through the results.

But I need to be able to grab specific rows that meet this condition. Something following this pseudo code:

$query = "SELECT *
          FROM translations
          WHERE iddoc = '$id'
          AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_arrayofrows($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)

and so on...

How can I do this?

3
  • 1
    why not put the extra condition in the Where clause ? Commented Aug 25, 2012 at 23:05
  • Is that the best (only) way to do it? I can't return an array of all of the results? Commented Aug 25, 2012 at 23:05
  • 3
    http://www.php.net/manual/en/mysqli-result.fetch-all.php, I guess this should help Commented Aug 25, 2012 at 23:06

3 Answers 3

7

You can try something like this

$arrayofrows = array();
while($row = mysqli_fetch_array($result))
{
   $arrayofrows = $row;
}

You can now have

$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
Sign up to request clarification or add additional context in comments.

2 Comments

OOOH that's sneaaaky. I could even name it as a function and use it globally.
while($arrayofrows[] = mysqli_fetch_array($result)) or use of mysqli_fetch_all would be enough.
3

I think the function you are looking for is mysqli_fetch_all as shown below. This avoids the need to create an extra looping structure or a function to do something already provided.

$query = "SELECT *
          FROM translations
          WHERE iddoc = '$id'
          AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_all($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)

Comments

2

It depends on whether you require the entire result set back or not but I think the LIMIT could be used like:

$query = "SELECT *
          FROM translations
          WHERE iddoc = '$id'
          AND submitted = 1 LIMIT 200,200;";

Otherwise as others say you will need to convert to an array (which is what fetch_all does) and then get the element from that array.

1 Comment

Thanks @Sammaye, as a matter of fact if only a set of consecutive rows is needed, the LIMIT {[offset,] row_count | row_count OFFSET offset}] is perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.