Php 如何使用PDO处理带有'ln'的文本

Php 如何使用PDO处理带有'ln'的文本,php,javascript,html,sql,pdo,Php,Javascript,Html,Sql,Pdo,我正在使用PDO执行查询。我有这个问题:我有一个元素,我从中获取文本并将其发布到服务器端,并在我使用PDO prepare进行准备后将其添加到数据库中: $insertQuery = $db->prepare("INSERT INTO feedback (userName, comment, time_stamp, languageCode, userIp) VALUES (:usernaem, :comment, '". $now ."', :lang, '". $ip ."')");

我正在使用PDO执行查询。我有这个问题:我有一个
元素,我从中获取文本并将其发布到服务器端,并在我使用PDO prepare进行准备后将其添加到数据库中:

$insertQuery = $db->prepare("INSERT INTO feedback (userName, comment, time_stamp, languageCode, userIp) VALUES (:usernaem, :comment, '". $now ."', :lang, '". $ip ."')");
$insertQuery->bindValue(':comment',nl2br($_POST['comment']));
...
在我的web中的其他地方,我从db中获取此“注释”,并将其提取到json字符串:

  try {
    $commentQuery = $db->query("SELECT userName, time_stamp, comment, languageCode FROM feedback LIMIT 10");
  } catch (PDOException $ex) {
    die(json_encode(array('outcome' => false, 'message' => $ex->getMessage())));
  }

  $result = $commentQuery->fetchAll(PDO::FETCH_ASSOC);}
  $commentsJson = json_encode($result);
我要插入到某个javascript变量中的
$commentsJson

var comments = JSON.parse('<?php echo $commentsJson; ?>');
var comments=JSON.parse(“”);
在这里,我的chrome浏览器抛出了一个异常

例如: 如果我的
中有此文本: 我将其提交给db:

这是一些评论

这是新的评论

在数据库中,它保存为:

This is some comment<br />
and this is new line of comment
这是一些评论
这是新的评论
但当我从db那里得到它时,我得到的是:

 var comments = JSON.parse('[{"userName":"Test","time_stamp":"2013-04-04 10:17:43","comment":"This is some comment<br \/>\nand this is new line of comment", ...
var comments=JSON.parse(“[{”userName:“Test”,“time_stamp:“2013-04-04 10:17:43”,“comment:“这是一些注释\n这是新的注释行”。。。
之后,我的浏览器异常会说:

“未捕获的语法错误:意外标记”


感谢您的帮助!

好的,经过半天的研究,我做了以下几点:

<?php
$result = $commentQuery->fetchAll(PDO::FETCH_ASSOC);
$commentsJson = json_encode($result);
?>
...
function replacetext(text, what, to){
      var searchfor = what.replace(/\r/gi,'').replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
      var replacewith = to.replace(/\r/gi,'');
      var flags = 'gi';
      var searchexp = new RegExp(searchfor,flags);
      text = text.replace(searchexp,replacewith);
      return text;
   }

    var tmp = '<?php echo $commentsJson; ?>';
    tmp = replacetext(tmp, "\n", '<br>');

...
函数replacetext(text、what、to){
var searchfor=what.replace(/\r/gi').replace(/[-[\]{}()*+?,\\^$\\\s]/g,“\\$&”);
var replacewith=to.replace(/\r/gi',);
var标志='gi';
var searchexp=新的RegExp(searchfor,标志);
text=text.replace(searchexp,replacewith);
返回文本;
}
var tmp='';
tmp=replacetext(tmp,“\n”,“
”);

谢谢你的帮助!

你能帮我一个忙并运行你的json吗?它会指出任何格式错误的部分,这样我们就可以知道这是json的问题还是javascript的问题。好的,试着用这个答案来删除br,我不确定你是否会使用它。在这个步骤中,你可以将fetch all更改为foreach,然后在“注释”部分,将br改为新行。老实说,我真的不知道你的代码有什么问题。如果它是有效的json代码,那么json.parse就不会出错。我只是想解决一些我认为可能错误的问题。我添加了(并编辑了问题)
$insertQuery->bindValue(':comment',nl2br($_POST['comment']);
函数。