I need to retrieve data from several rows and then insert the results into an enumerated array so then I can use a ‘for’ loop to echo it…
I have this (I already connected to the database):
$genres_sql = 'SELECT genreID FROM genres WHERE imdbID = ?'; if ($stmt->prepare($genres_sql)) { // bind the query parameters $stmt->bind_param('i', $movieid); // bind the results to variables $stmt->bind_result($genre); // execute the query $stmt->execute(); $stmt->fetch(); }
Here I get the first result (row) into a variable. But I need to insert it into an enumerated array so the I can echo each result using this:
if (!empty($genre)) { for ($i = 0; $i + 1 < count($genre); $i++) { echo $genre[$i].', '; } echo $genre[$i]; }
This will echo: $genre[0], $genre[1], $genre[2], and so on until the last one.
I know that mysql_fetch_row can do the work, but I’m new to programming so I need a very detailed explanation.. Thank you!!
You can loop using the
MySQLi_Statement::fetchmethod:Basically
fetchprovides an iterator that thewhilecan use to iterate through each result. The variables inbind_result(in this case$genre) are reassigned with each iteration.