You are fetching a single row into PHP array with this line:
$choices = $result->fetch_assoc();
Then you use that array in your while
loop:
while ($row = $choices->fetch_assoc())
You can't call fetch_assoc()
on an array!
What you should have done is fetched all rows into a multi-dimensional array and then foreach
on that array.
$result = mysqli_query($conn, $query);
$choices = $result->fetch_all(MYSQLI_ASSOC);
// and then loop:
foreach($choices as $row) :
$result
is an object of mysqli_object class. Working directly with this object can be difficult. It is recommended to fetch all records into an array with fetch_all()
. You can then change the array, filter, loop, access specific rows, etc. You can't do it with the mysqli_result object and the methods for reading row by row can be confusing.
You can loop on mysqli_result directly though, which is much better than while ($row = $choices->fetch_assoc())
. The biggest advantage is that it will always loop from the beginning to the end, so you can loop it many times without rewinding. For example:
$result = $conn->query('SELECT * FROM users LIMIT 3'); // 3 rows returned
var_dump($result->fetch_all(MYSQLI_ASSOC)); // <-- this works
var_dump($result->fetch_all(MYSQLI_ASSOC)); // <-- this will not work without rewiding
// both of the loops will work
foreach ($result as $row) {
var_dump($row);
}
foreach ($result as $row) {
var_dump($row);
}
A foreach
loop is also cleaner and easier to understand. You run a query and then you loop on the result.
Of course, mysqli_result object is not an array. You can loop on it, but you can't access specific rows via array index. This will not get you the first row:
mysqli_query($conn, '...')[0]; // <-- Uncaught Error: Cannot use object of type mysqli_result as array
You should be using prepared statements if you have variable input in your SQL. Your queries fixed should look like this:
$stmt = $conn->prepare("SELECT * FROM choices WHERE question_number = ?");
$stmt->bind_param('i', $number);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
// echo HTML
}