MySQLi - Real Escape String

语法

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

定义和用法

它转义字符串中的特殊字符以在 SQL 语句中使用。

示例

试试下面的例子 −

<?php
   $servername = "localhost:3306";
   $username = "root";
   $password = "";
   $dbname = "TUTORIALS";
   $conn = new mysqli($servername, $username, $password, $dbname);
   
   if (!$conn->real_connect($servername, $username, $password, $dbname)) {
      die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
   }
   echo 'Success... ' . mysqli_get_host_info($conn) . "
";
   $id = mysqli_real_escape_string($conn, $_POST['id']);
   $name = mysqli_real_escape_string($conn, $_POST['name']);
   
   $sql = "INSERT INTO tutorials_auto (id, name)
   VALUES ('$id', '$name')";

   if (!mysqli_query($conn,$sql)) {
      die('Error: ' . mysqli_error($conn));
   }
   echo "1 record added";

   $conn->close();
?>

上述代码的示例输出应该是这样的 −

Success... localhost:3306 via TCP/IP 1 record added

mysqli_useful_functions.html