如何使用PHP插入特殊字符int mysqldb

时间:2017-03-04 06:39:24

标签: php mysql mysqli

我正在尝试使用php将特殊字符(实体)插入到mysql数据库中。

    <?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

1 个答案:

答案 0 :(得分:0)

尝试设置字符集以使转义按预期工作,然后再调用mysql_real_escape_string()

mysql_set_charset("utf8mb4");

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

编辑:我刚刚注意到您使用了被删除的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

相关问题