Search code examples
phpmysqlmysql-real-escape-string

how to escape characters from external source to insert into database?


insert.php is behind htaccess/passwd

It is grabbing data from an external source and then converting this into variables for insertion to database.

I am getting a mysql error that I believe is being caused by the existence of left and right parentheses ie (some text here) in the external source.

I've used mysql_real_escape_string but it doesn't seem to be working in this case.

$con = mysql_connect("localhost","user_name","password");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("user_dbname", $con);

// escape characters
$escaped_value = mysql_real_escape_string($var);

$sql = "INSERT INTO data (field1, field2, field3, field4, field5, field6)
        VALUES ('$_POST[field1]','$_POST[field2]','$_POST[field3]','$_POST[field4]',
                '$field5','$escaped_value', )";
;

Solution

  • You've got a comma after the last data field which is causing the query to fail. Also, you should refer to the $_POST array variables as $_POST['field1'] and not $_POST[field1]

    Try

    $sql = "INSERT INTO data (field1, field2, field3, field4, field5, field6)
        VALUES ('".$_POST['field1']."','".$_POST['field2']."','".$_POST['field3']."','".$_POST['field4']."',
                '$field5','$escaped_value')";
    

    Effectively, mysql_real_escape_string is the least of your problems. :)