What are the best practices for integrating PHP scripts with MySQL databases for data manipulation in a forum setting?

When integrating PHP scripts with MySQL databases for data manipulation in a forum setting, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input before inserting it into the database to ensure data integrity. Lastly, consider implementing proper error handling to gracefully handle any database connection or query errors.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum_db";

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

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

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
$stmt->bind_param("ss", $title, $content);

// Sanitize user input
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$content = filter_var($_POST['content'], FILTER_SANITIZE_STRING);

// Execute the prepared statement
$stmt->execute();

// Handle any errors
if ($stmt->error) {
    echo "Error: " . $stmt->error;
}

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