What are some common pitfalls when connecting a PHP form to a database?

One common pitfall when connecting a PHP form to a database 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 interact with 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 a statement with a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

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

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