5

我需要从几行中检索数据,然后将结果插入到枚举数组中,这样我就可以使用“for”循环来回显它......

我有这个(我已经连接到数据库):

$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();
}

在这里,我将第一个结果(行)放入一个变量中。但是我需要将它插入到一个枚举数组中,这样我就可以使用这个来回显每个结果:

if (!empty($genre)) {
for ($i = 0; $i + 1 < count($genre); $i++)
{
    echo $genre[$i].', '; 
}
echo $genre[$i];
}

这将回显:$genre[0], $genre[1], $genre[2],等等,直到最后一个。

我知道mysql_fetch_row可以完成这项工作,但我是编程新手,所以我需要一个非常详细的解释.. 谢谢!

4

4 回答 4

2

我对 mysqli 不是 100% 熟悉,但我玩过很多 pgsql 命令来做这种事情,我认为你要找的是mysqli-result->fetch_assoc。这将产生一个关联数组,您可以像这样轻松地循环它:

while ($row = $result->fetch_assoc()) {
    printf ($row["genre"]);
}

编辑: Alnitak的解释比我在这个答案的评论中得到的更好。

于 2009-03-09T16:50:14.993 回答
1

您可以使用以下方法循环MySQLi_Statement::fetch

$stmt->bind_result($genre);
$stmt->execute();
$genres = array();
while ($stmt->fetch()) {
    $genres[] = $genre;
}

基本上fetch提供了一个迭代器,while可以用来迭代每个结果。bind_result(在这种情况下)中的变量在$genre每次迭代时都会重新分配。

于 2009-03-09T16:46:19.543 回答
1

这并不是问题的真正答案,但是如果您想将数组打印为逗号分隔的列表,最好使用implode命令而不是 for 循环:

//Replaces the for loop in the question
echo implode(', ', $genre);

...除了最后一个元素后没有逗号。

于 2009-03-09T17:10:05.477 回答
0

只是为了完成@Mykroft 的回复,如果你真的只是想要一个枚举数组,只需使用 $result->fetch_array(MYSQLI_NUM),尽管关联数组在大多数情况下使用起来非常简单。

于 2009-03-09T16:53:26.017 回答