【问题标题】:Saving data to database from textarea将数据从 textarea 保存到数据库
【发布时间】:2013-12-24 16:15:57
【问题描述】:

我是 PHP 新手。我只想知道为什么每次我从 textarea 保存字符串数据时,它总是在数据库中插入<p> string </p> 格式。这是我的代码:

 <table>
  <tr>
   <td>  
    <textarea name="event_desc" cols="40" rows="10" id="event_desc"></textarea>
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="Add" id="Add" value="Add event" /></td>
  </tr>
 </table>

每次我包含一个单引号('),它总是显示为" &amp; #39;",没有空格。这是示例输出:

input: test2 ' (and every space i made count)
<p>    test2 &#39; &nbsp;&nbsp; $</p>

我已经使用了 mysql_real_escape_string、addslashes 和 stripslashes。

这是我保存到数据库的代码:

 <?php 
 if(isset($_REQUEST['Add']))
 { 
  $event_title=$_POST['event_title'];                                                                         $event_desc=mysql_real_escape_string($_POST['event_desc']);
  $section=$_POST['section'];
  $get_date=NOW;
  if($event_title=="" || $event_desc=="")
  {
    echo'<div class="warning">Some of the fields are empty.</div>';
  }
  else
  {
    mysql_query("INSERT INTO events (`event_title`, `event_desc`,`event_date`,`event_target`) VALUE('$event_title','$event_desc','$get_date','$section')") or die(mysql_error('Error: Error in adding entries'));
    echo'<div class="success">You have just added 1 event for School. You will be redirect in  5 seconds</div>';
    echo "<META HTTP-EQUIV='Refresh' CONTENT='5; URL=events.php'>";
  }
 }
 ?>

谢谢大家的帮助。

【问题讨论】:

  • 你连接数据库的方式是什么?你用的是mysql还是mysqli还是pdo?
  • 我使用 mysql 先生 @Kiyarash

标签: php html mysql textarea


【解决方案1】:

我的建议是使用 mysqli::real_escape_string 和 prepared statements
点击mysqli::real_escape_string

【讨论】:

    【解决方案2】:

    您可以在存储到数据库时使用addslashes(),如果编码为htmlspecialchars_decode,则用于检索

     <?php
    $str = "<p>this -&gt; &quot;</p>\n";
    
    echo htmlspecialchars_decode($str);
    
    // note that here the quotes aren't converted
    echo htmlspecialchars_decode($str, ENT_NOQUOTES);
    ?>
    

    输出:

    <p>this -> "</p>
    <p>this -> &quot;</p>
    

    参考:http://www.php.net/manual/en/function.htmlspecialchars-decode.php

    【讨论】:

      【解决方案3】:

      除了上面提到的传统方法。

      我们可以使用“base64_encode”对来自文本区域的字符串进行编码,然后存储在数据库中......同时从数据库中检索使用“base64_decode”函数将其解码。

      注意:- 根据文档,它消耗 33% 以上的空间。

      参考:-http://php.net/manual/en/function.base64-encode.php

      【讨论】:

        【解决方案4】:

        您将 html 编码的文本保存到数据库中。在页面中查看时对标点进行编码。所以你必须如何解码它们。我不是 PHP 人,但我知道这是你的问题。

        【讨论】:

          猜你喜欢
          • 2013-12-15
          • 2015-02-06
          • 2016-01-21
          • 2015-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-15
          • 2018-07-21
          相关资源
          最近更新 更多