5

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!!

0

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

AFAIK, it's not possible to mix "fetch_assoc" with "execute". The former needs a "result set" object, as returned by "query", whilst the latter works with a "statement" object.
see stackoverflow.com/questions/627197/…, where I've tried to explorer this difference more fully
1

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.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.