()

2013-05-27 3 views
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)); 

그러나, 이것은 나에게 데이터베이스에 중복 된 결과를주고있다. 즉, 15 내가 6 개 요소 범위 강제 30 요소 수행되는 시험 횟수를 (아닌 다른 반복 얻고있다.

를 또한, I (1) 다수의 삽입 이후에 var_dump(array_diff(range(1, 6), $Used)); 쓰면, 항상. 그래서, 분명히, 숫자 2와 6이 고려되지 않는 array(2) { [1]=> int(2) [5]=> int(6) }를 출력합니다. 그리고 난에 echo $Photo;를 할 경우 분명히 삽입의 문제가 아니다, 그래서 (2), 숫자는 항상 1 또는 5 있습니다.

그래서 데이터베이스의 항목이 중복되는 이유 PHP 코드의 문제점은 무엇입니까? 필드 고유의 제약 조건이 있지만 임의의 사진 ID를 저장하는 PHP는 수정되지 않습니다.

답변

0

어리석은 나, 나는 내가 알고 있다고 생각했던 것을 다시 읽음으로써 그것을 해결했다. array_rand (물론) returns the KEY of the array. 따라서 다음과 같이 작동합니다.

// 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));