user2579439
user2579439

Reputation: 1243

how to load properly sql data with a new line

im trying to query my database and when im using the code below, it repeats some part of the data

$data = $result['testdata'];
$data = str_replace("\r\n", "<br>", $data);
$data = str_replace("\r", "<br>", $data);
$data = str_replace("\n", "<br>", $data);

echo "<form action='testsearch.php' method='post'>";

echo"<tr>"; 
echo  "<td align='center' width='auto'>" . $result['test'] . "<input type=hidden name=test value=" . $result['test'] . "' /> </td>";
echo  "<td align='left' width='500'>" . $data . "<input type=hidden name=testdata value=" . $data . "' /> </td>";
"</tr>"; 

here is the snapshot of the result of the code above:

Code1

now when i try to use htmlentities in the code to resolve the issue im losing the new line and being replace instead by <br>

$data = $result['testdata'];
$data = str_replace("\r\n", "<br>", $data);
$data = str_replace("\r", "<br>", $data);
$data = str_replace("\n", "<br>", $data);
$data1 = htmlentities($data);

echo "<form action='testsearch.php' method='post'>";

echo"<tr>"; 
echo  "<td align='center' width='auto'>" . $result['test'] . "<input type=hidden name=test value=" . $result['test'] . "' /> </td>";
echo  "<td align='left' width='500'>" . $data1 . "<input type=hidden name=data1 value=" . $data1 . "' /> </td>";
"</tr>"; 

here is the snapshot of the second code:

Code2

i need help in maintaining the new line and at the same time not repeating the datas fetch from mysql db...

Upvotes: 0

Views: 28

Answers (1)

Barmar
Barmar

Reputation: 782717

You're missing the quotes at the beginning of the value attributes. And you need to convert HTML special characters to entities only when they're inside attributes, not in the text. So it should be:

echo  "<td align='center' width='auto'>" . $result['test'] . "<input type=hidden name=test value='" . htmlspecialchars($result['test']) . "' /> </td>";
echo  "<td align='left' width='500'>" . $data . "<input type=hidden name=data1 value='" . htmlspecialchars($data) . "' /> </td>";

Upvotes: 1

Related Questions