What are the potential security risks of directly inserting user input into a MySQL database in PHP?

Directly inserting user input into a MySQL database in PHP can lead to SQL injection attacks, where malicious SQL queries are injected into the input fields. To prevent this, use prepared statements with parameterized queries to sanitize and validate user input before inserting it into the database.

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

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

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind parameters to the query
$stmt->bind_param("ss", $user_input1, $user_input2);

// Set the user input values
$user_input1 = $_POST['input1'];
$user_input2 = $_POST['input2'];

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

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