0

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?

2
  • Are you really using the same $result variable for both queries, or did you change that when copying the code? Commented Jan 3, 2019 at 21:43
  • I don't see anything here that will generate more words each time. I suspect the problem is in the // some code here. Commented Jan 3, 2019 at 21:48

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

That seems to be the solution to a different problem. I don't see how this error would cause him to get more than one word on each iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.