Nigel does provide a solution, but lets go over the other glaring issues. I've re-written your code, making two major changes, you still may need to do some tweaking as I'm not familiar with your db or other named variables.
1 - Prepared Statement
How it helps and what is does Instead of re-answering this for the hundredth time, other people do a much better job of explaining it:
How can prepared statements protect from SQL injection attacks?
Helper function - You'll want this after you get a better understanding of how prepared statements work.
https://phpdelusions.net/mysqli/simple
2 - OOP
I rewrote this in the Object-Oriented syntax. I find it a lot less verbose and usually a bit easier to understand. What you win with the syntax change you loose with doing prepared statements as generally they involve more steps (but for the greater good)
$sql2 = "SELECT a_id, u_id, answer, a_datetime, user_id, username FROM answer LEFT JOIN user ON answer.u_id = user.user_id WHERE q_id = ?";
$stmt -> $con -> prepare($sql2);
$stmt -> bind_param("s", $pid);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($aid, $uid, $answer, $date, $userid, $username);
echo '<table border=2>';
while($stmt -> fetch()) {
echo '<tr>';
echo '<td>Answered by: '. $username .'</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $answer .'</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $date .'</td>';
echo '</tr>';
}
echo '</table>';
$stmt -> free_result();
$stmt -> close();
$con -> close();
While we're picking hairs, you should try not to echo so much HTML. You can close php inside a while
loop and it will work the same. I fixed some of the HTML issues you have as well. (Should be using <tbody>
, and just for fun I threw a <thead>
in there too
// after bind result in the code above
?>
<table>
<thead>
<th>Answered by</th>
<th>Answer</th>
<th>Date</th>
</thead>
<tbody>
<?php
while($stmt -> fetch()) {
?>
<tr>
<td><?php echo $username;?></td>
</tr>
<tr>
<td><?php echo $answer;?></td>
</tr>
<tr>
<td><?php echo $date;?></td>
</tr>
<?php
}
?>
</tbody>
</table>