使用"mysql_fetch_row"从数据库检索结果并使用PHP和mysqli插入数组? [英] Use "mysql_fetch_row" to retrieve results from database and insert into array using PHP and mysqli?

查看:42
本文介绍了使用"mysql_fetch_row"从数据库检索结果并使用PHP和mysqli插入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从几行中检索数据,然后将结果插入枚举数组中,以便随后可以使用"for"循环来回显它...

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];
}

这将回显:$genre[0], $genre[1], $genre[2],,依此类推,直到最后一个.

This will echo: $genre[0], $genre[1], $genre[2], and so on until the last one.

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

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

推荐答案

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

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

基本上,fetch提供了一个迭代器,while可以使用该迭代器遍历每个结果.每次迭代都会重新分配bind_result中的变量(在本例中为$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.

这篇关于使用"mysql_fetch_row"从数据库检索结果并使用PHP和mysqli插入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆