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
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(); 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?
$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.
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.
“PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”
PDO is the new improved way to talk to your database. PDO has prepared statements which make your website faster/safer because:
A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server. It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks.
精彩评论