如何使用mysqli_real_escape_string函数

280 阅读2分钟

mysqli_real_escape_string是PHP的一个内置函数,用于控制不需要的和危险的字符。 在这篇文章中,我们将借助一个例子来讨论什么是mysqli_real_escape_string函数,以及如何使用它来保护数据库。

什么是mysqli_real_escape_string?

根据定义,mysqli_real_escape_string()允许字符串中的特殊字符通过SQL查询转义到数据库中,同时考虑到当前建立的连接的字符集。简单地说,这个函数允许将特殊字符视为字符串的一部分并作为字符串保存在数据库中。黑客大多使用特殊字符,如 ?, ',^,%, 和 !, 来入侵数据库或滥用数据库的数据,所以为了防止这种行为,使用这个函数来强制将 PHP 视为字符串。这个函数的一般语法如下。

mysqli_real_escape_string(connection_variable, string_variable)

在一般的语法中,connection_variable是存储在任何变量中的mysqli_connect()函数的结果, string_variable是应该通过这个函数来转义字符的变量。例如,我们创建了一个PHP代码,首先我们使用函数mysqli_connect()建立PHP与数据库的连接,参数为localhost;数据库在同一台机器上,用户名;maadi,密码;qwer1234和数据库的名称;Organization。然后我们应用if-else条件,通过使用函数mysqli_real_escape_string(connection_variable, string_variable)来检查连接是否建立成功。在确保连接成功建立后,我们将声明变量,命名为,Firstname,并分配一些包括一些特殊字符的字符串,然后将其插入数据库Linuxhint中。

<?php
//Establishment of Connection with databas
$connection = mysqli_connect("localhost","maadi","Organization");

//checking status of connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " .mysqli_connect_error();
    exit();
}
//declare variable
$firstname2 ="John'o Alexander";

//inserting into the database
$sql="INSERT INTO Linuxhint (Emp_name) VALUES ('$firstname2')");

//execution of mysql queries
$r = mysqli_query($connection, "INSERT into Linuxhint VALUES ('firstname2')");
if(!$r){
    print("Error occurred\n");
}
else{
    print("Record inserted successfully\n");
}
//connection closed
mysqli_close($connection);
?>

这段代码的输出应该是一个错误,因为字符串之间含有特殊字符'。为了检查输出结果,在Ubuntu中打开终端,使用php命令运行这个PHP文件,并使用保存代码的文件名。

$ php file1.php

出现了错误,为了纠正这个错误,我们将使用mysqli_real_escape_string()并将字符串保存在数据库中。

<?php
//Establishment of Connection with databas
$connection = mysqli_connect("localhost","maadi","Organization");

//checking status of connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " .mysqli_connect_error();
    exit();
}

//declare variable
$firstname2 ="John'o Alexander";

//pass from the mysqli_real_escape_string()
$firstname = mysqli_real_escape_string($connection,$firstname2);
//inserting into the database
$sql="INSERT INTO Linuxhint (Emp_name) VALUES ( '$firstname' )");

//execution of mysql queries
$r = mysqli_query($connection, "INSERT into Linuxhint VALUES ('firstname')");
if(!$r){
    print("Error occurred\n");
}
else{
    print("Record inserted successfully\n");
}
//connection closed
mysqli_close($connection);
?>

再次在终端运行该文件。

$ php file1.php

输出是成功的。为了验证它,我们将进入MySQL并运行以下命令来检查字符串是否被插入数据库。

SELECT * FROM Linuxhint;

结论

保护文件的安全是每个人都关心的问题,因为它们可能包括一些机密数据。通常在黑客攻击中,特殊字符被用来连接数据库以获取其数据用于不道德的用途。为了防止这种情况,我们可以在数据插入数据库之前对其进行各种安全检查。在这篇文章中,我们讨论了PHP的一个内置函数,它是用来确保安全的方式,即没有特殊字符在数据库中互动来伤害它。相反,这个函数认为它是一个正常的字符串,并将该字符串插入数据库。