0
我正在制作一个游戏,其中多个房间可以同时运行。我有一个MySQL表“房间”来保存有关所有房间的信息。PHP - 循环访问数据库中只有一些字段的最佳做法
该表中的字段包括房间中的“id”,房间的数字ID以及“user1”到“user6”的数字ID。
在一个页面上,我必须做一些东西,这些信息对于所有的房间,我当前的代码是一样的东西:
//query() is just a function which implements mysqli::query with logging,
// error handling, etc. It uses the same connection on each call so
// there is no overhead of opening a new connection.
$q = query("SELECT id,some_other_fields,user1,user2,user3,...,user6 FROM rooms");
while($r = $q->fetch_assoc()){
//some stuff here
foreach(array($r['user1'],$r['user2'],...,$r['user6']) as $user)
stuff((int)$user);
//some more stuff
}
正如你所看到的,我必须明确地做出了一个数组用户并通过它进行循环。
有没有更好的方法来做到这一点?
而且我正在考虑这个代码:
$q = query("SELECT id,some_other_fields FROM rooms");
while($r = $q->fetch_assoc()){
//some stuff here
foreach(query("SELECT user1,user2,user3,...,user6 FROM rooms WHERE id=".$r['id'])->fetch_assoc() as $user)
stuff((int)$user);
//some more stuff
}
如果房间数通常应在10〜20,这会是合适的?
理想情况下,您希望尽可能少地使用SQL语句。如果选择用户的唯一原因是循环访问,则可以使用['CONCAT_WS'](http://dev.mysql.com/doc/refman/5.0/zh/string-functions.html#function_concat-ws )把他们拉入一个变量,然后['爆炸'](http://www.php.net/manual/en/function.explode.php)他们在一个数组。 – Jon 2013-02-17 03:51:42
在给定的房间里总是有六个用户?这就是球员的数量? – FoolishSeth 2013-02-17 03:53:57
玩家的最大数量是6,但并不总是刚好6.“0”表示“没有用户”。 (并且'stuff'会对此作出适当的反应) – TwiNight 2013-02-17 04:39:59