1The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.
2
3Object oriented style:
4$mysqli -> real_escape_string(escapestring)
5
6$mysqli = new mysqli("localhost","my_user","my_password","my_db");
7
8// Escape special characters, if any
9$firstname = $mysqli -> real_escape_string($_POST['firstname']);
10$lastname = $mysqli -> real_escape_string($_POST['lastname']);
11$age = $mysqli -> real_escape_string($_POST['age']);
12
13Procedural style:
14mysqli_real_escape_string(connection, escapestring)
15
16$con = mysqli_connect("localhost","my_user","my_password","my_db");
17
18// Escape special characters, if any
19$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
20$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
21$age = mysqli_real_escape_string($con, $_POST['age']);
1$str = addslashes('What does "yolo" mean?');
2echo($str);
3$str = addcslashes('What does "yolo" mean?','?');
4echo($str);
1$str = addslashes('What does "yolo" mean?'); // for either ' or "
2echo($str);
3$str = addcslashes('What does "yolo" mean?','?'); // specify charaters to preceed by \
4echo($str);
1/*
2The addslashes() function returns a string with backslashes in front of predefined characters.
3
4The predefined characters are:
5
6single quote (')
7double quote (")
8backslash (\)
9NULL
10
11Tip: This function can be used to prepare a string for storage in a database and database queries.
12*/
13
14// Example usage:
15$str = addslashes('What does "yolo" mean?');
16echo($str);
17
18// Expected Output: What does \"yolo\" mean?