What do I need to escape when sending a query?

前端 未结 11 1235
执念已碎
执念已碎 2021-01-07 18:01

When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website.

I usually just have a function escape_string(blah),

相关标签:
11条回答
  • 2021-01-07 18:31

    I would also escape comments (double dash)

    --
    
    0 讨论(0)
  • 2021-01-07 18:36

    In PHP, I'm using this one and I'll appreciate every comment about it :

    function quote_smart($valeur) 
    { 
        if (get_magic_quotes_gpc()) 
            $valeur = stripslashes($valeur); 
    
        if (!is_numeric($valeur)) 
            $valeur = mysql_real_escape_string($valeur); 
    
        return $valeur; 
    }
    
    
    $IdS = quote_smart($_POST['theID']); 
    $sql = " 
    SELECT * FROM Students 
    WHERE IdStudent={$IdS}; 
    ";
    

    Needs one more verification if a field can be NULL :

    $picture = NULL;
    $theidyouwant = 7;
    $Name = 'WOOD';
    
    
    if(is_null($picture)) 
        $p = 'NULL'; 
    else
        $p = "'".quote_smart($picture)."'"; 
    
    $IdS = quote_smart($theidyouwant);
    
    $requete = "SELECT * FROM Students
        WHERE IdStudent={$IdS} AND
        PictureStudent={$p} AND
        NameStudent='{$Name}';
        ";
    

    That's it enjoy ! (hope the post will correctly send underscores and not &#95 ;)

    0 讨论(0)
  • 2021-01-07 18:38

    Use prepared statements.

    0 讨论(0)
  • 2021-01-07 18:43

    Use Prepared/Parameterized queries!

    0 讨论(0)
  • 2021-01-07 18:45

    A great thing to use in PHP is the PDO. It takes a lot of the guesswork out of dealing with securing your SQL (and all of your SQL stuff in general). It supports prepared statements, which go a long way towards thwarting SQL Injection Attacks.

    A great primer on PDO is included in the book The PHP Anthology 101 Essential Tips, Tricks & Hacks by Davey Shafik etc. 2nd Ed. Makes learning a breeze and is excellent as a reference. I don't even have to think about anything other than the actual SQL Query anymore.

    0 讨论(0)
  • 2021-01-07 18:49

    Which language are using? It seems like pretty much all of them have built-in SQL escape functions that would be better to use.

    For example, PHP has mysql_real_escape_string and addslashes.

    0 讨论(0)
提交回复
热议问题