0

我有以下脚本:

// Query
$STH = $DB->prepare('SELECT * FROM players WHERE game = ?');
$STH->execute(array($_POST['game']));

// Get the stored photos
$Used = array();
while ($row = $STH->fetch())
  $Used[] = intval($row['photo']);

// (1)

// Get a random photo that is not stored already
$Photo = array_rand(array_diff(range(1, 6), $Used));

// (2)

// Insert the photo
$STH = $DB->prepare('INSERT INTO players (id, user, game, name, family, photo) VALUES (?, ?, ?, ?, ?, ?)');
$STH->execute(array($Id, $User->id, intval($_POST['game']), $Name, $Family, $Photo));

但是,这在数据库中给了我重复的结果。具体来说, the1和 the5被重复了很多次(而不是其他我执行的测试,大约 30 个元素来强制 6 个元素的范围。

var_dump(array_diff(range(1, 6), $Used));此外,如果我在多次插入后写入(1),它总是输出array(2) { [1]=> int(2) [5]=> int(6) }. 因此,显然,没有考虑数字 2 和 6。如果我echo $Photo;在(2)中这样做,数字总是1or 5,所以这显然不是插入的问题。

那么,为什么数据库中的条目会重复呢?我的 PHP 代码有什么问题?将来我肯定会设置一个 2 字段唯一约束,但这不会修复保存随机照片 ID 的 PHP。

4

1 回答 1

0

愚蠢的我,我只是通过重新阅读我认为我知道的内容来解决它: array_rand (当然)返回数组的 KEY。因此,它的工作方式如下:

// Query
$STH = $DB->prepare('SELECT * FROM players WHERE game = ?');
$STH->execute(array($_POST['game']));

// Get the stored photos
$Used = array();
while ($row = $STH->fetch())
  $Used[] = intval($row['photo']);

// Get a random photo that is not stored already
$Array = array_diff(range(1, 6), $Used);
$PhotoKey = array_rand($Array);
$Photo = $Array[$PhotoKey];

// Insert the photo
$STH = $DB->prepare('INSERT INTO players (id, user, game, name, family, photo) VALUES (?, ?, ?, ?, ?, ?)');
$STH->execute(array($Id, $User->id, intval($_POST['game']), $Name, $Family, $Photo));
于 2013-05-27T05:25:57.053 回答