is this safe in terms of SQL injection?

别说谁变了你拦得住时间么 提交于 2019-12-06 15:02:20

问题


Currently getting more and more into MySQL. It's something i haven't been too fussed about but i want to write some scripts with it now.

My question is simple, im making a search script and just want to know if my php code can prevent some SQL injections.. the code:

$orig = $_POST['term'];
$term = mysql_real_escape_string($orig);
$sql = mysql_query("select * from db1 where content like '%$term%' ");

Is this ok? Alternatively if anyone has an easier/better/safer way of doing this plese feel inclined to let me know.


回答1:


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
}



回答2:


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.




回答3:


yes it should be fine with mysql_real_escape_string




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/5735948/is-this-safe-in-terms-of-sql-injection

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