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 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊