如何从PHP中的表中返回多行使用mysql [英] How to return multiple rows from a table in in php using mysql

查看:165
本文介绍了如何从PHP中的表中返回多行使用mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定为我的家人建立一个梦幻足球的网站,但是我从数据库中返回了多行。

I've decided to build a website for fantasy football for my family but am getting stuck with returning multiple rows from the database.

我想要的:一个单一的sql调用,并获得玩家的整个列表,所以我可以填充一个对象或对象列表。 (如果整个表可以返回,那将是巨大的...)。我的目标是让可用播放器的列表只是显示给用户。

What I want: to make a single sql call and get the entire list of players so I can populate an object or list of objects. (if the whole table could be returned that would be great...). My goal is to have the list of available players to be drafted simply displayed to the user.

目前我可以看到一些结果,当测试通过以下方法(信用:从php文档...)。然而,我不能因为发生了什么而感到失落。我不能让这在我的大脑中有意义。

Currently I can somewhat see some results when testing by the following method (credit: from the php docs...). However I can't help be feel lost as to what is going on.. I can't make this make sense in my brain.

// My query
$sql = mysql_query("SELECT * FROM players");

//$data = mysql_fetch_array($sql);
while ($row = mysql_fetch_array($sql, MYSQL_NUM)) {
    printf("Name: %s <br/>", $row[1]);
}

这似乎打印了每个播放器的名称。然而
'mysql_fetch_array()'如何迭代每行作为while循环迭代?此外,由于有多个列如何访问每个列...这必须硬编码,如:

This seems to print the names of each player. However how does 'mysql_fetch_array()' iterate each row as the while loop iterates? Further, since there are multiple columns how can I access each column... does this have to be hardcoded such as:

while ($row = mysql_fetch_array($sql, MYSQL_NUM)) {
    printf("Name: %s <br/>", $row[1]);
    printf("Team: %s <br/>", $row[2]);
    ..
    .
    printf("Team: %s <br/>", $row[5]);
}

最后,我将使用将相关日期存储在roster对象或某物:

Eventually I will replace the print statements with code that will store relevant date in a roster object or something:

class Roster(){

    $playerName;
    $team;
    $etc.
}

上面的while循环方法很难和笨重。有更好的方法来访问所有返回的行吗?其他人怎么试图这样?我有限的经验是C#和sql服务器,它可以做一些惊人的东西,一些毫不费力的配置...立即返回一个列表^

The while loop method above feels difficult and clunky. Is there a better way to access all returned rows? How would someone else attempt this? My limited experience is C# and sql server, which can do some amazing stuff with some effortless configuration... immediately return a list ^

如果我不清楚,我会请稍后再回来评论。我还是一名CS学生。非常感谢您的耐心等待。

If I'm not clear I will check back soon and comment further. I'm still a CS student. Thank you for your patience.

推荐答案

试试这个,

 while($row_data = mysql_fetch_array($row_data))
 {
  $row_player_name = $row_data['column_name_player'];
  $row_team = $row_data['column_team'];
  echo $row_player_name;
  echo $row_team;
}

column_name_player是包含播放器名称的表的列名。

column_name_player is the column name of table which contains player name.

这篇关于如何从PHP中的表中返回多行使用mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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