简体   繁体   English

如何保护此代码免受sql注入?

[英]How to protect this code from sql injection?

Hey all, I made a textbox which autocompletes input by getting stuff from a database and it works like this now: 嘿,我做了一个文本框,它通过从数据库中获取内容来自动完成输入,现在它的工作方式如下:

<script type="text/javascript">
$().ready(function() {
    $("#food").autocomplete("get_course_list.php", {
        width: 260,
        cacheLength: 10,
        matchContains: false,

        //mustMatch: true,
        //minChars: 0,
        //multiple: true,
        //highlight: false,
        //multipleSeparator: ",",
        selectFirst: true

    });
});
</script>

and this in the .php file: 这在.php文件中:

<?php
require_once "config2.php";
$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "select DISTINCT voedsel as voed from voedingswaarden where voedsel LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $cname = $rs['voed'];
    echo "$cname\n";
}
?>

But now i read about sql injections etc so I wanted to protect my php script against that with mysql_real_escape_string(); 但是现在我读到了有关sql注入的知识,所以我想用mysql_real_escape_string()来保护自己的php脚本。 but I can't seem to get it to work. 但我似乎无法使其正常工作。 Any ideas how to implement this in my .php file and if this is enough protection? 有什么想法如何在我的.php文件中实现这一点,以及是否有足够的保护措施?

$q = strtolower($_GET["q"]);

becomes 变成

$q = mysql_real_escape_string(strtolower($_GET["q"]));

your connection to the db must be established and there must be only one link, but that is the case otherwise your mysql_query wouldnt work correctly. 您必须建立与数据库的连接,并且必须只有一个链接,但是这种情况下,否则mysql_query无法正常工作。

the code is not very elegant but it'll work. 该代码不是很优雅,但可以正常工作。

you may want to change that: 您可能需要更改以下内容:

if (!$q) return;

to

if (strlen($q) == 0) return;

I have said this before but I think mysql_real_escape_string() should be depecrated and you should use PDO instead. 我之前已经说过,但是我认为mysql_real_escape_string()应该废除,而应该使用PDO

“PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.” “ PDO – PHP数据对象–是数据库访问层,提供了访问多个数据库的统一方法。”

PDO is the new improved way to talk to your database. PDO是与数据库对话的改进的新方法。 PDO has prepared statements which make your website faster/safer because: PDO准备了一些使您的网站更快/更安全的声明,原因是:

A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server. 预准备语句是预编译的SQL语句,可以通过仅将数据发送到服务器来执行多次。 It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks. 它具有自动使占位符中使用的数据免受SQL注入攻击的影响的附加优点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM