MySQL error when inserting data containing apostrophes (single quotes)?

前端 未结 10 1066
不知归路
不知归路 2020-11-30 13:59

When I an insert query contains a quote (e.g. Kellog\'s), it fails to insert a record.

ERROR MSG:

You have an error in your SQL s

10条回答
  •  無奈伤痛
    2020-11-30 14:35

    Optimized for multiple versions of PHP

    function mysql_prep($value){
            $magic_quotes_active = get_magic_quotes_gpc();
            $new_enough_php = function_exists("mysql_real_escape_string");//i.e PHP>=v4.3.0
            if($new_enough_php){//php v4.3.o or higher
                //undo any magic quote effects so mysql_real_escape_string( can do the work
                if($magic_quotes_active){
                    $value = stripslashes($value);  
                }
                $value = mysql_real_escape_string(trim($value));
            }else{//before php v4.3.0
                //if magic quotes arn't already on, add slashes  
                if(!$magic_quotes_active){
                    $value = addslashes($value);
                //if magic quotes are already on, shashes already exists        
                }   
    
            }
            return $value;
        }
    

    Now just use:

    mysql_prep($_REQUEST['something'])
    

提交回复
热议问题