我希望cronjob函数将所有allusers2的钱更新为1,而只增加第一行并增加9.(有10个用户)。我尝试将for循环换成for循环并得到相同的结果。我尝试将$ database-> fetch转换为mysqli_fetch_array并使用相同的结果并将其转换为mysqli_fetch_all,这给了我"注意:未定义的索引://变量名称"对于所有数据库变量。
class allusers2
{
public $id;
public $level;
public $money;
private $database;
// Methods (functions)
public function __construct($allusers_id, $database)
{
$this->database = $database;
$allusers_id = (int)$allusers_id;
$result = $this->database->query("SELECT * FROM `users` WHERE `id`='$allusers_id'");
if($this->database->num_rows($result) == 0) {
throw new Exception("allusers does not exist!");
}
$allusers = $this->database->fetch($result);
$this->id = $allusers['id'];
$this->level = $allusers['level'];
$this->money = $allusers['money'];
}
public function update()
{
$this->database->query("UPDATE `users` SET
`level` = '{$this->level}',
`money` = '{$this->money}'
WHERE `id`='{$this->id}'");
}
}
function cronjob()
{
global $database;
global $player;
global $self_link;
require('allusers2.php');
$result = $database->query("SELECT id FROM `users`");
$allusers_id = $database->fetch($result);
$allusers2 = new Allusers2($allusers_id, $database);
while($allusers_id = $database->fetch($result)) {
$allusers2->money += 1;
$allusers2->update();
}
}
答案 0 :(得分:1)
如果您确实要更新所有记录,并将金额增加相同金额,那么您不需要先选择记录并循环遍历它们 - 数据库可以执行一次性适合你:
UPDATE users SET money = money + 1
答案 1 :(得分:0)
您只会更新第一位用户:
$result = $database->query("SELECT id FROM `users`");
$allusers_id = $database->fetch($result); // Extract the first user
$allusers2 = new Allusers2($allusers_id, $database); // Create object for first user
while($allusers_id = $database->fetch($result)) {
$allusers2->money += 1; // Keep updating that first user
$allusers2->update();
}
你需要不进行第一次获取,并将Allusers2移动到循环中:
while($allusers_id = $database->fetch($result)) {
$allusers2 = new Allusers2($allusers_id, $database); // Now you're creating a new object for each user
$allusers2->money += 1;
$allusers2->update();
}