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

前端 未结 10 1017
不知归路
不知归路 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:30

    Escape the quote with a backslash. Like 'Kellogg\'s'.


    Here is your function, using mysql_real_escape_string:

    function insert($database, $table, $data_array) { 
        // Connect to MySQL server and select database 
        $mysql_connect = connect_to_database(); 
        mysql_select_db ($database, $mysql_connect); 
    
        // Create column and data values for SQL command 
        foreach ($data_array as $key => $value) { 
            $tmp_col[] = $key; 
            $tmp_dat[] = "'".mysql_real_escape_string($value)."'"; // <-- escape against SQL injections
        } 
        $columns = join(',', $tmp_col); 
        $data = join(',', $tmp_dat);
    
        // Create and execute SQL command 
        $sql = 'INSERT INTO '.$table.'('.$columns.')VALUES('. $data.')'; 
        $result = mysql_query($sql, $mysql_connect); 
    
        // Report SQL error, if one occured, otherwise return result 
        if(!$result) { 
            echo 'MySQL Update Error: '.mysql_error($mysql_connect); 
            $result = ''; 
        } else { 
            return $result; 
        } 
    }
    
    0 讨论(0)
  • 2020-11-30 14:33

    You should pass the variable or data inside mysql_real_escape_string(trim($val)), where $val is the data on which you are getting an error.

    If you enter the text, i.e., "I love Kellog's", we have a ' in the string so it will break the query. To avoid it you need to store data in a variable like this $val = "I love Kellog's".

    Now, this should work:

    $goodval = mysql_real_escape_string(trim($val));
    
    0 讨论(0)
  • 2020-11-30 14:35

    User this one.

    mysql_real_escape_string(trim($val));
    
    0 讨论(0)
  • 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'])
    
    0 讨论(0)
提交回复
热议问题