dongpu1879 2018-03-15 09:44
浏览 42
已采纳

为什么我不必再次在SELECT上重新获取表单数据?

For my simple application where I chose to write my own solution for blog comments, I'm doing these 3 steps:

1. Taking data from basic HTML form inputs via POST, then escaping the strings like this:

$komentar = htmlspecialchars($_POST['komentar'], ENT_QUOTES, 'UTF-8');

2. Using PDO for db insertion:

$stmt = $conn->prepare("INSERT INTO komentare (id, jmeno, komentar, clanek) VALUES (DEFAULT, ?, ?, ?)");
    $stmt->bind_param("sss", $jmeno, $komentar, $clanek);
    $stmt->execute();
    $stmt->close();
    $conn->close();

3. Listing the results back using plain SELECT and loop-echoing like this:

$sql = "SELECT jmeno, komentar FROM komentare WHERE clanek = '$clanek' ORDER BY id DESC";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {
      while($row = $result->fetch_assoc()) {
          $zviratkoNum = rand(1,10);
          $vypis_jmeno = $row["jmeno"];
          $vypis_komentar = $row["komentar"];
          echo "<div class='radek'><span class='jmeno zviratka-". $zviratkoNum ."'>". $vypis_jmeno. "</span><span class='komentar'>" . $row["komentar"] . "</span></div>";
      }
  } else {
      echo "<h5>Zatím zde nejsou žádné komentáře</h5>";
  }
  $conn->close();

I thought it's a bad practice because while I escape the input (hopefully properly), I'm retrieving data back not escaped. But to my surprise, it get's echo'ed into DOM as a text (screenshot from my real test comment):

enter image description here

  1. Why?
  2. Is it bad practice?

Thanks in advance, Adam

  • 写回答

2条回答 默认 最新

  • dongyuan1983 2018-03-15 09:48
    关注

    htmlspecialchars converts a string of text into a format suitable for inserting into an HTML document.

    A database is not an HTML document. Characters with special meaning in HTML (such as &) generally have no special meaning in a database.

    So you are:

    1. Taking text and converting it to HTML source code
    2. Taking HTML source code and putting it in a database
    3. Taking HTML source code out of the database and converting it to HTML source code (so it is *double) encoded and gives you the HTML that will display HTML source code)
    4. Putting that into an HTML document

    When escaping data, do so just before you put it in the data format you are escaping it for.

    Don't convert to HTML before putting it into the database. Do that only before you put it into the HTML document.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应