Use “mysql_fetch_row” to retrieve results from database and insert into array using PHP and mysqli?
Question
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!!
Solution
You can loop using the MySQLi_Statement::fetch
method:
$stmt->bind_result($genre);
$stmt->execute();
$genres = array();
while ($stmt->fetch()) {
$genres[] = $genre;
}
Basically fetch
provides an iterator that the while
can use to iterate through each result. The variables in bind_result
(in this case $genre
) are reassigned with each iteration.
OTHER TIPS
I'm not 100% familiar with mysqli but I've played with a lot of pgsql commands doing this sort of thing and i think what your looking for is mysqli-result->fetch_assoc. This will produce an associative array that you can loop over pretty easily like so:
while ($row = $result->fetch_assoc()) {
printf ($row["genre"]);
}
EDIT: Alnitak has linked to better explanation than i have in the comments for this answer.
This isn't really an answer to the question, but if you want to print out an array as a comma-separated list, it's better to use the implode command than a for loop:
//Replaces the for loop in the question
echo implode(', ', $genre);
...except that there's no comma after the last element.
Just to complete @Mykroft reply, if you really just want an enumerated array just use $result->fetch_array(MYSQLI_NUM), although and associative array is much simple to use in most situations.