What are common pitfalls when using PHP to insert data into a database via a form?

One common pitfall when using PHP to insert data into a database via a form is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely insert data into the database.

// 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);
}

// Prepare and bind the SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Set parameters and execute
$value1 = $_POST['input1'];
$value2 = $_POST['input2'];
$stmt->execute();

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