dongmu4591 2013-04-07 12:40
浏览 33
已采纳

转义mysql搜索字符串php [复制]

This question already has an answer here:

I have a question regarding best practices involving a search form with PHP/MySql

Consider the following:

  • A search form to search for book titles
  • A jQuery / AJAX request to "auto-suggest" titles
  • Need to escape and how?

The mysql user which connects to the database only has the SELECT privilege at the moment but I might add the INSERT privilege in the future (thus potential for injections).

The search form is simple, such as this:

<form id="search" method="GET" action="/search/">
  <input type="text" value="" id="s" name="s" />
</form>

The form sends via GET to search.php?s=Search Query. Once there, the PHP file is something like the following:

<?php

  $s = $_GET['s']; // the search request

  $search = new Search($s); // creates new search object and sends the $s query

  echo $search->output;  // returns results

?>

My Search class has the following:

class Search {

  // Database stuff omitted

 $stmt->bindParam(':search', $this->query, PDO::PARAM_STR)
 $stmt->execute;
 $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
 $this->output = $res;

}

My sql query is this: SELECT booktitle FROM books WHERE booktitle LIKE '%:search%'

What problems might I get into? Do you have any suggestions as to what needs to be escaped and where? Do you see potential problems with my setup? Concerns such as sql injections?

</div>
  • 写回答

1条回答 默认 最新

  • dpswo40440 2013-04-07 13:51
    关注

    Parameters are automatically escaped in prepared PDO statements, you're doing it right.

    Just be noticed that you don't need the quotes in your query:

    $stmt = $myPDO->prepare("SELECT booktitle FROM books WHERE booktitle LIKE :search");
    $stmt->bindParam(':search', "%".$this->query."%", PDO::PARAM_STR);
    $stmt->execute();
    

    Or even simpler:

    $stmt = $myPDO->prepare("SELECT booktitle FROM books WHERE booktitle LIKE ?");
    $stmt->execute( array("%".$this->query."%") );
    

    More info: Are PDO statements automatically escaped?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号