2017-03-04 20 views
0

我想插入特殊字符(實體)到MySQL數據庫使用PHP。如何插入特殊字符int mysqldb使用PHP

<?php 
    $servername = "localhost"; 
    $username = "root"; 
    $password = ""; 
    $dbname = "test"; 

$autoid = $_REQUEST["autoid"]; 
// $explanation = htmlspecialchars($_REQUEST["explanation"]); 
$explanation = mysql_real_escape_string("<p>hello how are you Ê</p>"); 



    echo $explanation; 

    // Create connection 
    $conn = new mysqli($servername, $username, $password, $dbname); 

    //$explanation = utf8_decode(trim(mysql_real_escape_string($explanation)); 
    // Check connection 
    if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
    } 

    $sql = "UPDATE question_master SET explanation='$explanation' WHERE autoid=$autoid"; 

    if ($conn->query($sql) === TRUE) { 
     echo "Record updated successfully"; 
    } else { 
     echo "Error updating record: " . $conn->error; 
    } 

    $conn->close(); 
?> 

我嘗試通過字符串是<p>hello how are you Ê</p>但MySQLdb的更新後,它成爲<p>hello how are you Ê</p>。我是mysql新手,不知道出了什麼問題。

表覈對是utf8mb4_bin表覈對是utf8_bin

+0

http://stackoverflow.com/questions/8568301/how-to-insert-special-language-characters -in-php-into-mysql-database – ashanrupasinghe

+0

ADD「」 –

回答

0

嘗試設置的字符集,使逃避工作的期望的呼叫mysql_real_escape_string()這樣前:

mysql_set_charset("utf8mb4"); 

$explanation = mysql_real_escape_string("<p>hello how are you Ê</p>"); 

編輯:我剛剛注意到你使用depraated mysql_real_escape_string() ..相反,你應該使用mysqli_real_escape_string()。更具體地說,您最好通過將鏈接標識符傳遞給MySQL連接來爲特定連接設置字符集。所以,去正確的方法是這樣的:

$conn = new mysqli($servername, $username, $password, $dbname); 

mysqli_set_charset($conn, "utf8mb4"); 

$explanation = mysqli_real_escape_string($conn, "<p>hello how are you Ê</p>"); 

文檔: http://php.net/manual/en/mysqli.set-charset.php http://php.net/manual/en/mysqli.real-escape-string.php