Retrieving the nth element of the mysqli query result

With the old mysql_ syntax mysql_ I was able to do something like this:

 $query=mysql_query('select id from rank'); for ($i=0; $i<$max; $i++) { $id0[$i] = mysql_result($query, $i, "id"); $id1[$i] = mysql_result($query, $i+1, "id"); $id2[$i] = mysql_result($query, $i+2, "id"); } 

I find many difficulties in achieving the same result with mysqli ; I usually retrieve the mysqli query data using the mysqli_fetch_assoc($query) function to recursively retrieve all records as a result of the query from row to row.

How to get the result that I need, i.e. to extract the nth, nth + 1, nth + 2 element of the query result in each cycle of the recursive function? And how can I access the nth element of the id field itself? It seems to me impossible to work with one line of the query result at a time ...

Sorry if this question seems silly, but I am in the process of converting an old site made with mysql_ syntax to mysqli_ , and I have many difficulties even if I try to access PHP.net (and, of course, knowing ... ) ...

EDITOR (SOLVING THE PROBLEM) : I solved my problem following the recommendations of Jeroen: without the fetch_all function, I created an array that stores each row of the msqli query result through a loop:

  while ($row=mysqli_fetch_assoc($query)) $table[]=$row; 

Thus, it is much easier to point to each table entry using regular indexes:

 for ($i=0; $i<$max; $i++) { $id0[$i]=$table[$i]["id"]; $id1[$i]=$table[$i+1]["id"]; $id2[$i]=$table[$i+2]["id"]; } 
+5
source share
1 answer

You can use mysqli_data_seek() to set the result pointer to an arbitrary string in your result set.

So your code will look something like this:

 for ($i=0; $i<$max; $i++) { mysqli_data_seek($result, $i); // depending on your php version you might need a temporary variable to // get the ID $id0[$i] = mysqli_fetch_assoc($result)['id']; ... } 
+3
source

Source: https://habr.com/ru/post/1205961/


All Articles