PHP mysqli_real_escape_string() 函数



定义和用法

mysqli_real_escape_string() 函数用于转义字符串中的字符,使其在 SQL 语句中合法使用。

语法

mysqli_real_escape_string($con, $str)

参数

序号 参数和描述
1

con(必填)

这是一个表示与 MySQL 服务器连接的对象。

2

str(必填)

这是您需要转义特殊字符的字符串。

返回值

mysqli_real_escape_string() 返回一个合法的字符串,可用于 SQL 查询。

PHP 版本

此函数首次在 PHP 5 版本中引入,并在所有后续版本中有效。

示例

以下示例演示了 mysqli_real_escape_string() 函数的使用(以过程式风格)−

//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Creating a table
mysqli_query($con, "CREATE TABLE my_team(Name VARCHAR(255), Country VARCHAR(255))");

$player = "S'Dhawan";
$country = "India";

//Inserting a record
$res = mysqli_query($con, "INSERT into my_team VALUES ('$player', '$country')");
if(!$res){
   print("Error occurred");
}else{
   print("Record inserted successfully");
}
	
print("\n");
	
$player = mysqli_real_escape_string($con, $player);
$country = mysqli_real_escape_string($con, $country);

//Inserting a record
$res = mysqli_query($con, "INSERT into my_team VALUES ('$player', '$country')");
if(!$res){
   print("Error occurred");
}else{
   print("Record inserted successfully");
}


//Closing the connection
mysqli_close($con);
?>

这将产生以下结果−

Error occurred
Record inserted successfully

示例

在面向对象风格中,此函数的语法为 $con->real_escape_string(); 以下是此函数在面向对象风格中的示例 $minus;

<?php
   //Connecting to the database
   $con = new mysqli("localhost", "root", "password", "test");

   //Creating a table
   $con->query("CREATE TABLE my_team(Name VARCHAR(255), Country VARCHAR(255))");

   $player = "S'Dhawan";
   $country = "India";

   //Inserting a record
   $res = $con->query("INSERT into my_team VALUES ('$player')");
   if(!$res){
      print("Error occurred");
   }else{
      print("Record inserted successfully");
   }
	
   print("\n");
	
   $player = $con->real_escape_string($player);

   //Inserting a record
   $res = $con->query("INSERT into my_team (Name) VALUES ('$player')");
   if(!$res){
      print("Error occurred");
   }else{
      print("Record inserted successfully");
   }

   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果−

Error occurred
Record inserted successfully

示例

<?php
   $con = mysqli_connect("localhost","root","password","mydb");
   
   if (mysqli_connect_errno($con)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   $myName = "Jr's";
   $myName = mysqli_real_escape_string($con,$myName);
   
   mysqli_query($con,"INSERT into emp (name) VALUES ('$myName')");
   mysqli_close($con);
php_function_reference.htm
广告