PHP——只在数据库中的某些字段中循环的最佳实践


PHP - Best practice to loop through only some fields in database

我正在制作一个可以同时运行多个房间的游戏。我有一个MySQL表"房间"来保存所有房间的信息。

该表中的字段包括房间的数字id"id"和房间中用户的数字id从"user1"到"user6"。

在一个页面上,我必须对所有房间的这些信息做一些事情,我目前的代码是:

//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间左右,这合适吗?

在执行查询之前创建一个字段数组,如以下

$fields = array('user1','user2','user3','user4');
$q = query("SELECT id,some_other_fields, ". implode($fields, ',') ." FROM rooms");
while($r = $q->fetch_assoc()){
    //some stuff here
    foreach($fields as $field)
        stuff((int)$r[$field]);
    //some more stuff
}

然后,您可以在只更改一行代码的情况下更改查询和循环。