Am I safe from SQL injection?

I use simple cms as a backend on my website where I can update news, etc. I want to be safe from SQL injection, so I wonder if this code is safe or if something I can do to make it more secure:

if($_POST) {
    if(isset($_POST['title']) and (isset($_POST['content']) and     ($_POST['added']))) {
        $title = "'".mysql_real_escape_string($_POST['title'])."'";
        $content = "'".mysql_real_escape_string($_POST['content'])."'";
        $added = "'".mysql_real_escape_string($_POST['added'])."'";

        if(isset($_POST['id']) && $_POST['id']!=''){
            $result = mysql_query("UPDATE news SET title = ".$title.",     added =".$added.", content = ".$content."  WHERE id = ".$_POST['id']);
            $msg = "News Updated Successfully";
        }else{
            $result = mysql_query("INSERT INTO news (title, content, added) values($title, $content, $added)") or die("err0r");
            $msg = "News Added Successfully";
        }
    }

Thank you, we have a great day!

+3
source share
3 answers

You do not disinfect $_POST['id'].

Do intval()it or (better) completely refuse processing if the identifier is not an integer (it is assumed that the identifier is a field int).

if (!is_numeric($_POST['id'])
 die ("Invalid ID");
+9
source

One thing you should do is make the shure ID integer (which probably should be):

$id = (int)$_POST['id'];
+3
source

- ,

Yes, you can use the PDO interface with prepared statements so that the request is built separately from the data (which are linked later), and no injection is possible.

+2
source

All Articles