What are best practices for processing and manipulating form data in PHP for database queries?

When processing form data in PHP for database queries, it is important to sanitize and validate the input to prevent SQL injection and other security vulnerabilities. One best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, it is recommended to use functions like htmlspecialchars() to prevent cross-site scripting attacks.

// Example of processing form data in PHP for a database query

// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate input data
    $name = htmlspecialchars($_POST["name"]);
    $email = htmlspecialchars($_POST["email"]);

    // Establish a database connection
    $conn = new mysqli("localhost", "username", "password", "database_name");

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

    // Prepare a SQL statement using a parameterized query
    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);

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

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

    echo "Data inserted successfully!";
}