【问题标题】:Use "mysql_fetch_row" to retrieve results from database and insert into array using PHP and mysqli?使用“mysql_fetch_row”从数据库中检索结果并使用 PHP 和 mysqli 插入数组?
【发布时间】:2010-10-12 05:44:51
【问题描述】:

我需要从几行中检索数据,然后将结果插入到枚举数组中,这样我就可以使用“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 可以完成这项工作,但我是编程新手,所以我需要一个非常详细的解释.. 谢谢!!

【问题讨论】:

    标签: php mysql arrays loops mysqli


    【解决方案1】:

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

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

    编辑:Alnitak 链接到的解释比我在 cmets 中对这个答案的解释更好。

    【讨论】:

    • AFAIK,无法将“fetch_assoc”与“execute”混合使用。前者需要一个“结果集”对象,由“查询”返回,而后者需要一个“语句”对象。
    • stackoverflow.com/questions/627197/…,我试图更充分地探索这种差异
    【解决方案2】:

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

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

    基本上fetch 提供了一个迭代器,while 可以使用它来迭代每个结果。 bind_result(在本例中为 $genre)中的变量会在每次迭代时重新分配。

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-09
          • 1970-01-01
          • 1970-01-01
          • 2016-05-15
          相关资源
          最近更新 更多