【问题标题】:How to handle text with `ln` using PDO如何使用 PDO 处理带有 ln 的文本
【发布时间】:2013-03-26 05:21:23
【问题描述】:

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

$insertQuery = $db->prepare("INSERT INTO feedback (userName, comment, time_stamp, languageCode, userIp) VALUES (:usernaem, :comment, '". $now ."', :lang, '". $ip ."')");
$insertQuery->bindValue(':comment',nl2br($_POST['comment']));
...

在我网络的其他地方,我从数据库中获取了这个“评论”并将其提取到 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);

$commentsJson 我正在插入一些 javascript 变量:

var comments = JSON.parse('<?php echo $commentsJson; ?>');

我的 chrome 浏览器在这里抛出异常。

例如:

如果我的&lt;textarea&gt; 中有此文本: 我将它提交给数据库:

这是一些评论

这是新的注释行

在数据库中保存为:

This is some comment<br />
and this is new line of comment

但是当我从数据库中取回它时,我得到了这个:

 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", ...

然后我的浏览器异常说:

"Uncaught SyntaxError: Unexpected token"

任何帮助将不胜感激!

【问题讨论】:

  • 你能帮我一个忙,通过jsonformatter.curiousconcept.com运行你的json。它会指出任何格式错误的部分,这样我们就可以知道这是 json 的问题还是 javascript 的问题。
  • 好的,尝试使用这个 SO 答案删除 br 的 stackoverflow.com/questions/2436145/…
  • 我不确定是否要使用它。在女巫步中?
  • 您可以将 fetch all 更改为 foreach,并在评论部分将 br 更改为新行。老实说,我真的不知道你的代码有什么问题。如果它是有效的 json 代码,那么 JSON.parse 不应该出错。我只是想解决我认为可能有问题的事情。
  • 我已经添加(并编辑了问题)$insertQuery-&gt;bindValue(':comment',nl2br($_POST['comment'])); 函数。

标签: php javascript html sql pdo


【解决方案1】:

好的,经过半天的研究,我做了这个:

<?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>');

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2018-05-26
    • 2012-03-16
    相关资源
    最近更新 更多