Escape special characters in a string:
<?php // Assume database username: root, password: 123456, database: CODERCTO $con=mysqli_connect("localhost","root","123456","CODERCTO"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"CREATE TABLE websites2 LIKE websites");$newname="Rookie'Tutorial";//The special characters in $newname are not escaped, and the execution fails mysqli_query($con,"INSERT into websites2 (name) VALUES ( '$newname')");// Escape special characters $newpers=mysqli_real_escape_string($con,$newname);// After escaping, insert and execute successfully mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newname')");mysqli_close($con);?>
The mysqli_real_escape_string() function escapes special characters in strings used in SQL statements.
mysqli_real_escape_string( connection,escapestring ) ;
parameter | describe |
---|---|
connection | Required. Specifies the MySQL connection to use. |
escapestring | Required. The string to escape. The encoded characters are NUL (ASCII 0), n, r, , ', ", and Control-Z. |
Return value: | Returns the escaped string. |
---|---|
PHP version: | 5+ |