PHP开发问答应用:数据库存储答案网页显示无换行问题求助
Let's break down the issues here and fix your line break problem step by step:
1. Critical Syntax Error in user.php
First off, you’ve got a PHP syntax mistake in your database query block that’s likely breaking the whole display logic before even getting to line breaks:
$sql = "SELECT * FROM q_form; $result = mysqli_query($conn, $sql);
You didn’t close the string for $sql before starting to assign $result. This will cause a parse error. Fix it by splitting the code into proper separate lines:
$sql = "SELECT * FROM q_form"; $result = mysqli_query($conn, $sql);
2. Incorrect Answer Parsing with explode(',', ...)
You’re splitting the answer content using commas, which makes no sense when your answers use line breaks (not commas) for formatting. This is completely destroying your original line structure. Remove that foreach loop and explode call—you don’t need it at all.
3. Fixing Line Breaks in Display
Now let’s get those line breaks showing up on the page. You have two reliable options:
Option 1: Use nl2br() (Convert Newlines to HTML <br> Tags)
This is the most straightforward approach for HTML. The nl2br() function takes the newline characters (\n) stored in your database and converts them to <br> tags that browsers recognize. Update your output code to:
echo nl2br(htmlspecialchars($row['answer']));
htmlspecialchars()keeps your content safe from XSS attacks (great call using this!), andnl2br()handles the line break conversion seamlessly.
Option 2: Use CSS white-space: pre-wrap
If you prefer not to modify the text with PHP, you can use CSS to tell the browser to respect newline characters directly. Wrap your answer in a container element and add this style:
First, update the output in user.php:
echo '<div class="answer-text">' . htmlspecialchars($row['answer']) . '</div>';
Then add this CSS to your <head> (or an external stylesheet):
.answer-text { white-space: pre-wrap; word-wrap: break-word; /* Makes sure long lines don’t overflow the container */ }
This will make the browser render newlines as line breaks and wrap text properly, without altering the original content from the database.
4. Double-Check Database Storage
Your signup.inc.php code uses mysqli_escape_string() which correctly preserves newline characters from the textarea, so the line breaks are being stored properly in the database—you don’t need to change anything there.
Fixed Code Block for user.php
Here’s the corrected full block for displaying answers:
<?php if (isset($_POST['submit'])) { $sql = "SELECT * FROM q_form"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($row = mysqli_fetch_assoc($result)) { echo nl2br(htmlspecialchars($row['answer'])); } } } ?>
That should resolve your line break issue completely!
内容的提问来源于stack exchange,提问作者Nelson

