Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

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?

like image 939
red23jordan Avatar asked Sep 29 '11 16:09

red23jordan


People also ask

How do I insert a single apostrophe in SQL?

The short answer is to use two single quotes - '' - in order for an SQL database to store the value as ' .

How do I add quotes to text in MySQL?

QUOTE () function in MySQL This function in MySQL is used to return a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\), single quote ('), ASCII NULL, and Control+Z preceded by a backslash.


2 Answers

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; 
    } 
}
like image 107
Shef Avatar answered Sep 27 '22 19:09

Shef


Replace mysql with mysqli. Use this

mysqli_real_escape_string($connection,$_POST['Description'])
like image 25
Nusrat Robina Avatar answered Sep 27 '22 20:09

Nusrat Robina