What potential security risks should be considered when connecting a form to a MySQL database in PHP?

One potential security risk when connecting a form to a MySQL database in PHP is SQL injection. To prevent SQL injection attacks, you should always use prepared statements with parameterized queries to sanitize user input before executing SQL queries.

// Establish a connection to the MySQL database
$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 SQL statement using a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Sanitize user input before executing the query
$value1 = mysqli_real_escape_string($conn, $_POST['input1']);
$value2 = mysqli_real_escape_string($conn, $_POST['input2']);

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

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