mysqli_real_escape_string()函数是PHP中的内置函数, 用于本义所有特殊字符以用于SQL查问。在将字符串插入数据库之前应用它, 因为它删除了可能烦扰查问操作的任何特殊字符。
当应用简略的字符串时, 它们中可能蕴含特殊字符, 例如反斜杠和撇号(尤其是当它们间接从输出了此类数据的表单中获取数据时)。这些被认为是查问字符串的一部分, 并且会烦扰其失常运行。
<?php $connection = mysqli_connect( "localhost" , "root" , "" , "Persons" ); // Check connection if (mysqli_connect_errno()) { echo "Database connection failed." ; } $firstname = "Robert'O" ;$lastname = "O'Connell" ; $sql ="INSERT INTO Persons (FirstName, LastName) VALUES ( '$firstname' , '$lastname' )"; if (mysqli_query( $connection , $sql )) { // Print the number of rows inserted in // the table, if insertion is successful printf( "%d row inserted.n" , $mysqli ->affected_rows);}else { // Query fails because the apostrophe in // the string interferes with the query printf( "An error occurred!" );} ?>
在下面的代码中, 查问失败, 因为应用mysqli_query()执行撇号时, 会将撇号视为查问的一部分。解决方案是在查问中应用字符串之前应用mysqli_real_escape_string()。
<?php $connection = mysqli_connect( "localhost" , "root" , "" , "Persons" ); // Check connection if (mysqli_connect_errno()) { echo "Database connection failed." ; } $firstname = "Robert'O" ;$lastname = "O'Connell" ; // Remove the special characters from the// string using mysqli_real_escape_string $lastname_escape = mysqli_real_escape_string( $connection , $lastname ); $firstname_escape = mysqli_real_escape_string( $connection , $firstname ); $sql ="INSERT INTO Persons (FirstName, LastName) VALUES ( '$firstname' , '$lastname' )"; if (mysqli_query( $connection , $sql )) { // Print the number of rows inserted in // the table, if insertion is successful printf( "%d row inserted.n" , $mysqli ->affected_rows);} ?>
输入如下:
1 row inserted.
更多数据库相干内容请参考:lsbin - IT开发技术:https://www.lsbin.com/
查看以下更多数据库相干的内容:
- PHP MySQL开发:https://www.lsbin.com/3083.html
- DBMS介绍:https://www.lsbin.com/2659.html
- 数据仓库介绍:https://www.lsbin.com/2652.html