is this safe in terms of SQL injection?

≯℡__Kan透↙ 提交于 2019-12-04 19:05:57

To avoid warnings in case $_POST['term'] isn't set:

if (isset($_POST['term'])) {
    $term = mysql_real_escape_string($_POST['term']);
    $sql = mysql_query("select * from db1 where content like '%$term%' ");
    // rest of sql query
}

Yes, it is safe from SQL injection. If you want to use a more systematic method of avoiding SQL injection issues I would recommend learning to use PDO and parameterised queries.

yes it should be fine with mysql_real_escape_string

The standard escaping is often insufficient for values used in the LIKE clause. Unless you want the user to specify % placeholders of his own, you should add:

 $term = mysql_real_escape_string($_POST['term']);
 $term = addcslashes($term, "%_");

To be precise, this only an issue for very large tables, where excessive %%%% placeholder injection in LIKE queries could decelerate the database server.

In your case mysql_real_escape_string will prevent SQL injection because it escapse single quotes and your string is set between single quotes. So in any case $term will always be just a simple string for SQL.

If you have something like

select * from A where id = $number

then no escaping would prevent an injection like:

0; drop A;

To prevent this scenario you would go well with prepared statements (PDO) or type-checking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!