Special characters can't be inserted into database Special characters can't be inserted into database wordpress wordpress

Special characters can't be inserted into database


Try mysql_real_escape_string();

mysql_connect("localhost","root","");    mysql_select_db("testdb");    $query="INSERT INTO keywords (id, keyword) VALUES ";    $handle = fopen("Ordlista.txt", "r");    if ($handle) {        $i=1;        while (($line = fgets($handle)) !== false) {            // process the line read.           // echo $line.'<br>';            if($i==1)            {            $query.=" ( NULL , '".mysql_real_escape_string($line)."') ";            $i++;            }            else {                $query.=" ,( NULL , '".mysql_real_escape_string($line)."') ";            }        }        $query.=";";     //   $qr=htmlspecialchars($query,ENT_QUOTES);        echo $query;        mysql_query($query);    } else {        echo 'error opening the file.';        // error opening the file.    }     fclose($handle);


The best solution would be to upgrade from mysql_* to PDO or mysqli_*, as these allow you to run prepared queries with parameters. But if you can't do that, you have to escape the data:

    while (($line = fgets($handle)) !== false) {        // process the line read.       // echo $line.'<br>';        $line = mysql_real_escape_string($line);        if($i==1)        {        $query.=" ( NULL , '".$line."') ";        $i++;        }        else {            $query.=" ,( NULL , '".$line."') ";        }    }


First, don't use the mysql extension. It has been officially deprecated.

Second, use a prepared statement with parameters to avoid any problems with SQL injection.

Third, make sure you're using a compatible connection, table and column encoding / character set.

For example, using mysqli...

$con = new mysqli('localhost', 'root', '', 'testdb');if ($con->connect_errno) {    throw new Exception($con->connect_error, $con->connect_errno);}$con->set_charset('utf8');$stmt = $con->prepare('INSERT INTO `keywords` (`keyword`) VALUES (?)');if (!$stmt) {    throw new Exception($con->error, $con->errno);}$stmt->bind_param('s', $keyword);foreach (file('Ordlista.txt') as $keyword) {    if (!$stmt->execute()) {        throw new Exception($stmt->error, $stmt->errno);    }}