What are the best practices for handling user input and database interactions in PHP?

When handling user input in PHP, it is essential to validate and sanitize the data to prevent SQL injection and other security vulnerabilities. To interact with a database securely, it is recommended to use prepared statements with parameterized queries to prevent SQL injection attacks.

// Example of handling user input and database interactions in PHP

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Validate and sanitize user input
$user_input = $_POST['user_input'];
$user_input = mysqli_real_escape_string($conn, $user_input);

// Prepare and execute a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $user_input);
$stmt->execute();

// Close the connection
$stmt->close();
$conn->close();