简体   繁体   English

PHP MySQLi转义引号

[英]PHP MySQLi escape quotes

I am using PHP/mysqli to read in comments, but various comments in the table have either a single quote or a double quote. 我正在使用PHP / mysqli读取注释,但是表中的各种注释都有单引号或双引号。

I am storing the comments in a data-attribute. 我将注释存储在数据属性中。 Using the Chrome console, I can see where the quote is throwing the whole code out of whack. 使用Chrome控制台,我可以看到引号将整个代码丢掉了。

 <?php
   echo "<td><a href='' class='comment' data-toggle='modal' data-comment='".htmlentities($row[comment])."'>" . $row[partner_name] . "</a></td>";
 ?>

As you can see in the code above, I tried to use htmlentities. 如您在上面的代码中看到的,我尝试使用htmlentities。 I also tried addslashes and a combination of the two. 我还尝试了addlashes和两者的结合。

Either way, I still can't get the comment to display properly because of the quote inside the mysql table. 无论哪种方式,由于mysql表中的引用,我仍然无法正确显示注释。

Is there another PHP function that I can use to fix this? 有没有另一个我可以用来解决这个问题的PHP函数?

在此处输入图片说明

Directly above is a screen shot from the Chrome console. 正上方是Chrome控制台的屏幕截图。 Right after the words POTENTIAL 53 there is a single quote that is throwing my code off. 在“ POTENTIAL 53”一词之后,有一个引号使我的代码无法使用。 All the other orange text is being read as HTML when it's supposed to be part of the comment. 当所有其他橙色文本应作为注释的一部分时,将被读取为HTML。

There has to be a way to read the single quote as part of the string. 必须有一种方法来读取单引号作为字符串的一部分。

Well, there are two problems: 好吧,有两个问题:

  1. You have to encode stuff, especially quotes: 您必须对内容进行编码,尤其是引号:

     $text = htmlentities($value, ENT_QUOTES); 
  2. The title attribute does not work with newlines, so you will have to deal that. title属性不适用于换行符,因此您必须进行处理。 Something like this should do the job: 像这样的事情应该做的工作:

     $text = preg_replace('/\\r?\\n/', '#xA;', $text); 

Pass the flag, ENT_QUOTES, to your htmlentities function. 将标志ENT_QUOTES传递到htmlentities函数。 See http://php.net/htmlentities . 参见http://php.net/htmlentities This will replace quotes with entified quote and prevent it from breaking out of the data-comment attribute. 这将用引号引起来的引号替换引号,并防止其脱离数据注释属性。

Try escaping the quotes in your data. 尝试转义数据中的引号。 Something to this affect: 可能影响到的事情:

$pattern = "/\"|\'/";
$replace = '\\\"';
$subject = $row[comment];
$rowComment = preg_filter($pattern, $replace, $subject);

*Tip - You can also filter the data before storing it. *提示-您还可以在存储数据之前过滤数据。

Description: echo $rowComment will produce a string with all quotes escaped; 说明:echo $ rowComment将产生一个所有引号都转义的字符串;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM