2013-04-07 120 views
0

我有一个关于涉及搜索表单用PHP/MySQL的摆脱MySQL的搜索字符串PHP

考虑以下最佳实践的问题:

  • 一个搜索表单搜索书名
  • 这个jQuery/AJAX请求以“自动建议”标题
  • 需要逃脱以及如何?

它连接到数据库MySQL的用户只有此刻的SELECT特权,但我可能会添加在将来INSERT特权(因此注射潜力)。

搜索表单很简单,如这样的:

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

的形式通过GET发送到search.php?s=Search Query。一旦出现,PHP文件是类似如下:

<?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 

?> 

我的搜索类有以下几点:

class Search { 

    // Database stuff omitted 

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

} 

我的SQL查询是这样的:SELECT booktitle FROM books WHERE booktitle LIKE '%:search%'

我可能会得到什么样的问题进?你有什么需要逃避和在哪里的建议?你看到我的设置有潜在的问题吗?诸如sql注入等问题?

回答

2

参数在准备好的PDO语句中自动转义,你做得对。

只是注意到,你并不需要在您的查询报价:

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

或者更简单:

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

更多信息:Are PDO statements automatically escaped?

+0

感谢您的回复,你的想法。 – 2013-04-07 17:24:20