简体   繁体   中英

Separate rows from a multi-row result in MySQL PHP

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!");
}

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM