I'm trying to pass a PHP variable holding a text value (html content) read from SQL database to a Javascript function. I'm trying all different approaches such as json_encode(utf8_encode())
and preg_replace()
but none of them seem to work.
Here's my code:
<?php
$db = new PDO('mysql:host=localhost;dbname=ramtin_data;charset=utf8', 'root', '');
foreach($db->query('SELECT * FROM posts') as $row)
{
$qtitle = $row['title'];
$qcontent = $row['content'];
$qpage = $row['page_id'];
$qcontent = json_encode(utf8_encode($qcontent));
echo "<script type='text/javascript'>
displayPost('$qtitle', '$qcontent');
</script>";
}
?>
Just want to mention that when I insert a row in my database with a simple line (including "
and /
) in the content
field, the above code works.
I've also tried the following code and got the same result:
$qcontent = preg_replace('/\v+|\\\[rn]/','<br/>', $qcontent);
The value inside the content
field in the database is the following string:
<img src="images/death_truck_titleDisplay.jpg" width="400" height="140" class="globalImageStyle" /><p class="postBodyContentParagraph">The work for another Construct2 game "<a href="http://ramt.in">Death Truck</a>" has been started.</p><p class="postBodyContentParagraph">I've had the idea since a few weeks ago and I'm amazed that how much it had developed into better shapes and more complex gameplay ideas only through the first weeks that I've started working on the graphics and the game codes/logic.</p><p class="postBodyContentParagraph">I'm actually done with the truck and pedestrian graphics and movement codes (plus the interaction code between pedestrians and the truck) and have included the game in the projects page as a Work In Progress. You can check some of the graphics and the idea of the whole game (plus some gameplay ideas) in the projects page.</p>
How should I pass the above value to the displayPost()
Javascript function?
UPDATE
The problem was with the single quotes inside the value. The accepted solution suggested all '
s to be replaced with \'
using $qcontent = str_replace("'", "\'", $qcontent);
which worked perfectly.
The result however was quoted by json_encode()
which I found the easiest way to remove the wrapping "
s to be using content.slice(1, content.length - 2)
(content
is the second parameter which refers to $qcontent
in the PHP section of the code) inside of the Javascript function.