sir_thursday
sir_thursday

Reputation: 5409

Mysqli fetch array nth row

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?

Upvotes: 5

Views: 9691

Answers (3)

user2072402
user2072402

Reputation: 31

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)

Upvotes: 3

codingbiz
codingbiz

Reputation: 26386

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)

Upvotes: 7

Sammaye
Sammaye

Reputation: 43884

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.

Upvotes: 2

Related Questions