user1264
user1264

Reputation: 61

PHP/MYSQL - Generate only one random word inside for loop

I am making a small interraction between a user and the computer in a game. The user is always the first one to make a move, where he inputs a word of his choise. I did a sql query that gets all plays made by the user while he is playing (maximun of 10 attempts). Once the user makes the first move I want the computer to generate a random word, like this:

$sql="Select word from plays where user=1 and id=$id";
$result=mysqli_query($link, $sql);

for($i=0;$i<10 && ($row=mysqli_fetch_assoc($result)) ;$i++){

    // some code here

    $random="select word from words order by Rand() LIMIT 1";
    $result=mysqli_query($link, $random);
    $wrandom=mysqli_fetch_assoc($result);
    $wordR=$wrandom['word']; 
 } 

In the first attempt all works correctly, a random word is generated but in the second attempt two random words are generated (instead of just one), in the third attempt, 3 words are generated and so on... What should I do to generate just one random word per attempt?

Upvotes: 0

Views: 194

Answers (2)

Barmar
Barmar

Reputation: 780974

You can join your two queries into a single query.

$sql = "SELECT p.word as user_word, w.word as computer_word
        FROM plays AS p
        CROSS JOIN words AS w
        WHERE p.user = 1 AND p.id = $id
        ORDER BY RAND()
        LIMIT 10";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $wordU = $row['user_word'];
    $wordR = $row['computer_word'];
    // some code here
}

Upvotes: 1

P&#248;ziel
P&#248;ziel

Reputation: 199

You should try to change the name of your variable $result in the loop because it creates a conflict with your first $result variable.

Upvotes: 0

Related Questions