Skip to content
PHP Logo

When should addslashes() and stripslashes() functions be used in PHP for data manipulation?

When dealing with user input that will be used in database queries or displayed on a webpage, it is important to use addslashes() to escape special characters that could potentially be used for SQL injection attacks. On the other hand, stripslashes() should be used when retrieving data from the database to remove any slashes that were added during the insertion process.

php
// Using addslashes() to escape special characters before inserting data into the database
$user_input = "John's comment";
$escaped_input = addslashes($user_input);
$query = "INSERT INTO comments (comment) VALUES ('$escaped_input')";
// Execute the query

// Using stripslashes() to remove slashes when retrieving data from the database
$query = "SELECT comment FROM comments WHERE id = 1";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$comment = stripslashes($row['comment']);
echo $comment;