What role do functions like addslashes() and stripslashes() play in securing PHP scripts that interact with databases?

Functions like addslashes() and stripslashes() play a crucial role in securing PHP scripts that interact with databases by escaping special characters that could potentially be used to inject malicious code into SQL queries. addslashes() adds a backslash before characters like quotes and slashes, while stripslashes() removes these added slashes before displaying data retrieved from the database.

// Example of using addslashes() and stripslashes() to secure PHP scripts interacting with databases

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Retrieve user input and sanitize it using addslashes()
$username = addslashes($_POST['username']);
$password = addslashes($_POST['password']);

// Insert the sanitized data into the database
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($connection, $query);

// Retrieve data from the database and use stripslashes() to display it safely
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
    $username = stripslashes($row['username']);
    echo "Username: $username <br>";
}

// Close the database connection
mysqli_close($connection);