What potential pitfalls should be considered when implementing a PHP script to write to a database and redirect on button click?

One potential pitfall to consider when implementing a PHP script to write to a database and redirect on button click is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements when interacting with the database to avoid SQL injection vulnerabilities.

<?php
// Establish a database connection
$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);
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize user input
    $data = mysqli_real_escape_string($conn, $_POST['data']);

    // Insert data into database using prepared statement
    $stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
    $stmt->bind_param("s", $data);
    $stmt->execute();

    // Redirect after database insert
    header("Location: success.php");
    exit();
}

$conn->close();
?>