19

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 syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's','Corn Flakes 170g','$ 15.90','$ 15.90','$ 14.10','--')' at line 1MySQL Update Error:

The first 's', should be Kellogg's.

Is there any solution?

Shef
  • 44,808
  • 15
  • 79
  • 90
red23jordan
  • 2,841
  • 10
  • 41
  • 57
  • 1
    How are you inserting that query, manually via command line, phpMyAdmin, or PHP? If it's the last one, then you are open to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) attacks. You should use a prepared statement abstraction class like PDO, or MySQLi. Or, the minimum of `mysql_real_escape_string`. – Shef Sep 29 '11 at 16:53
  • I am using PHP...so it is very hard to add \ before 's...i don't know when the string contains ' – red23jordan Sep 29 '11 at 17:06
  • 1
    If you are doing this in PHP, I already told you what and how you should do it. Either use PDO or MySQLi, or use `mysql_real_escape_string` before using a variable in a query. If you share your PHP code, then maybe we can suggest where you should use this function. – Shef Sep 29 '11 at 17:09
  • $product_array['CATEGORY'] = "Breakfast cereals"; $product_array['BRAND'] = "Kellogg's"; $product_array['NAME'] = "Corn Flakes"; insert(DATABASE, "price1", $product_array); – red23jordan Sep 29 '11 at 17:20
  • and the insert function is: 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[] = "'$value'"; } $columns = join(",", $tmp_col); $data = join(",", $tmp_dat); – red23jordan Sep 29 '11 at 17:20
  • # 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(mysql_error($mysql_connect)) { echo "MySQL Update Error: ".mysql_error($mysql_connect); $result = ""; } else { return $result; } } – red23jordan Sep 29 '11 at 17:20
  • I updated my answer with `mysql_real_escape_string` added to your function. – Shef Sep 29 '11 at 17:57
  • possible duplicate of [How to include a PHP variable inside a mysql insert statement](http://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-insert-statement) – Your Common Sense Sep 29 '11 at 18:01
  • Add your extra information to the question - not as a stream of comments. All else apart, you can format the question correctly and expansively; comments provide very limited formatting control. – Jonathan Leffler Sep 29 '11 at 18:24

10 Answers10

18

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; 
    } 
}
Shef
  • 44,808
  • 15
  • 79
  • 90
  • @DownVoter Care to give a reason? :) – Shef Sep 29 '11 at 18:27
  • 3
    @Col.Shrapnel I don't care if it runs or not, that's on another context. I am just giving an example where to use `mysql_real_escape_string` based on the OP's code. I didn't write that code, the OP did. – Shef Sep 29 '11 at 18:32
  • if you don't care if your code ever runs, why bother writing it? – Your Common Sense Sep 29 '11 at 18:35
  • @Col.Shrapnel Buddy, I am telling you again, it's not my code. It's OP's code. Look in the comments of the question, because the above function was dumped there. And now the function should run just fine. I am writing it to give to the OP a hint where to use the escaping function. – Shef Sep 29 '11 at 18:36
  • mysql_real_escape_string IS NOT "sanitizing" function and your example of using it is ridiculous. – Your Common Sense Sep 29 '11 at 18:37
  • THx all of you^^ It's my code..... I have tried... The line should be $tmp_dat[] = "'" . mysql_real_escape_string("$value") . "'"; – red23jordan Sep 30 '11 at 03:43
  • @red23jordan Yeah, it should be `$tmp_dat[] = "'" . mysql_real_escape_string($value) . "'";`. If your issue has been resolved feel free to accept an answer. Read [how does accepting an answer work?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) for more details on how and why to accept an answer. – Shef Sep 30 '11 at 06:54
5

Replace mysql with mysqli. Use this

mysqli_real_escape_string($connection,$_POST['Description'])
A J
  • 3,970
  • 14
  • 38
  • 53
Nusrat Robina
  • 51
  • 1
  • 1
3

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));
sashkello
  • 17,306
  • 24
  • 81
  • 109
user3272729
  • 181
  • 1
  • 4
2

You can also use the addslashes() function which automatically puts \ before ' to avoid error

ItalyPaleAle
  • 7,185
  • 6
  • 42
  • 69
faz
  • 21
  • 1
1

You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string) using a \.

Add a \ before the apostrophe in Kellogg's, giving you Kellogg\'s.

Mindgames
  • 118
  • 5
1

In standard SQL, you use two single quotes to indicate one single quote, hence:

INSERT INTO SingleColumn(SingleChar) VALUES('''');

The first quote opens the string; the second and third are a single quote; and the fourth terminates the string. In MySQL, you may also be able to use a backslash instead:

INSERT INTO SingleColumn(SingleChar) VALUES('\'');

So, in your example, one or both of these should work:

INSERT INTO UnidentifiedTable
    VALUES('Kellog''s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');
INSERT INTO UnidentifiedTable
    VALUES('Kellog\'s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');

In PHP, there is a function to sanitize user data (mysql_real_escape_string) before you embed it into an SQL statement -- or you should use placeholders. Note that if you do not sanitize your data, you expose yourself to SQL Injection attacks.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • since i am insert it using PHP, and i don't know when it appears ' – red23jordan Sep 29 '11 at 17:23
  • HEY, i add mysql_real_escape_string and it is ok now^^ THX ALL OF YOU – red23jordan Sep 29 '11 at 17:27
  • I wouldn't say mysql_real_escape_string sanitizing anything. And what about non-user input? – Your Common Sense Sep 29 '11 at 18:05
  • @Col. Shrapnel: what about non-user input? You get to decide whether it is 'deemed safe' or not. If you don't trust it, treat it as user input and sanitize it before embedding it in your SQL. If you trust it, then you don't have to do the sanitization. And why wouldn't you say 'mysql_real_escape_string()'? What would you recommend instead? I prefer placeholders, but many people don't, it seems. – Jonathan Leffler Sep 29 '11 at 18:14
  • so, you're saying `Kellog's` don't need to be escaped if coming not from user input or what? But okay, user unput. I am getting $limit from it, to use in LIMIT operator. would your mysql_real_escape_string() help me? – Your Common Sense Sep 29 '11 at 18:17
  • No; I'm saying that if you embed `Kellog's` into an SQL statement, you have to escape the apostrophe by some mechanism or other - but user data always needs to be sanitized and some non-user data might not need to be sanitized if you know it is sanitary already. If you don't know, you need to sanitize it. If you get `$limit` and know that it is numeric already, then you don't need to worry about `mysql_real_escape_string()` because it is a pure number and not a string. If you don't know whether `$limit` is numeric, then you need to check it first - but the checking is different for numbers. – Jonathan Leffler Sep 29 '11 at 18:23
  • you didn't say that. you have said only "use mysql_real_escape_string() to sanitize user data" which is most deceiving statement one ever seen. this function don't "sanitize" but merely escape delimiters, not from "user input" but from whatever source and not any "data" but merely strings only, leaving all other data types helpless and vulnerable – Your Common Sense Sep 29 '11 at 18:33
  • The discussion started from "You write two single quotes to get one into the database" (or backslash single quote); that remains true. If you include anything from a variable in an SQL statement, it is a string when copied into the SQL statement. If you control the data source, you know whether to worry about escaping it; if you don't control it, it is 'user input' and you need to worry about it. One way which usually works (and would work in the context of the question) is to use the `mysql_real_escape_string()` function. If you disagree, write your own answer and stop commenting on mine. – Jonathan Leffler Sep 29 '11 at 19:27
0

User this one.

mysql_real_escape_string(trim($val));
Harry
  • 87,580
  • 25
  • 202
  • 214
0

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'])
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
0

Escape it by using a helper function like:

function safeDBname($table_name)
{
  $outputText=str_replace("&#39;","",$outputText);
  return strtolower($outputText);
}
cagcak
  • 3,894
  • 2
  • 21
  • 22
0

i did it as below-

in my case description field contains apostrophe(').

and here is code:

$description=mysql_real_escape_string($description);

"insert into posts set name='".$name."', address='".$address."', dat='".$dt."', description='".$description."'";

it solved my problem

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
sanjaya
  • 204
  • 2
  • 4
  • 11