What do I need to escape when sending a query?

前端 未结 11 1291
执念已碎
执念已碎 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: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 _ ;)

提交回复
热议问题