-2

For the code below, $result will return 4 rows from my question_answers table which have the corresponding question_id.

At the moment I am fetching all 4 rows into the $answers variable. I was wondering how I could separate each row from the result and store them as separate variables so I could, say, printf them one at a time.

Thanks.

Edit: also, since the question_id column is an integer in the question_answers table and also in $question["question_id"], have I written my WHERE statement correctly? Thanks.

$result = mysqli_query($connection, 'SELECT  FROM questions_answers WHERE question_id='".$question["question_id"]."' ORDER BY RAND()'); //Runs the select query to get the possible answers to the randomly selected question
if(mysqli_num_rows($result)>0){
    $answers = mysqli_fetch_assoc($result);
    //printf each row individually
}
else{
    printf("ERROR: no answers for this question exist!");
}
  • 1
    no it is vulerable to sql injection see https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for guidance – nbk Oct 18 '21 at 20:21
  • 1
    @nbk Thanks but that doesn't really answer my question. I want to know if the code will work. Also you ignored the main point of my post. – iCookieMad Oct 18 '21 at 20:27
  • 1
    you should really read to the end and keep in mind to replicate – nbk Oct 18 '21 at 20:28

1 Answers1

0

You can do this like below:

$i=1;    
while(${"row" . $i} = mysqli_fetch_assoc($result)){$i++;};

So if there are 4 results, you will get the rows in $row1, $row2, $row3 and $row4;

But more standard way is to save the rows in array and use the array afterwards:

while($rows[] = mysqli_fetch_assoc($result));

In this case, you can access the rows like $rows['0'], $rows['1'], $rows['2'] and $rows['3']

Sultan
  • 637
  • 6
  • 14