Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting n-th element of a mysqli query result

With the old mysql_ syntax 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'm finding a lot of difficulties in reaching the same result with mysqli; usually I fetch the data of a mysqli query using the function mysqli_fetch_assoc($query) to extract recursively row by row all the records in the query result.

How can I obtain the result I need, i.e. extracting at each cycle of the recursive function the nth, nth+1, nth+2 element of the query result? And how can I refer to the nth element of the very id field? It seems impossible to me working with one row of the query result at a time...

Excuse me if this question appears to be silly, but I'm in the process of converting an old site made with the mysql_ syntax into mysqli_ and I'm encountering many difficulties even if i try to refer to PHP.net documentation (and of course to Stack Overflow knowledge...)...

EDIT (PROBLEM SOLVED): I've solved my problem following Jeroen's suggestions: being not available the fetch_all function, I created an array storing each row of the msqli query result through a loop:

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

Operating this way it's much easier pointing to each record of the table using the usual indexes:

for ($i=0; $i<$max; $i++) {
    $id0[$i]=$table[$i]["id"];
    $id1[$i]=$table[$i+1]["id"];
    $id2[$i]=$table[$i+2]["id"]; }
like image 295
Hunter Avatar asked Oct 20 '22 23:10

Hunter


1 Answers

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

So your code would look something like:

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'];
  ...
}
like image 117
jeroen Avatar answered Oct 24 '22 10:10

jeroen