What are the potential security risks associated with not properly escaping user input in PHP code when interacting with a MySQL database?

Not properly escaping user input in PHP code when interacting with a MySQL database can lead to SQL injection attacks, where malicious users can manipulate the database queries to access, modify, or delete data. To prevent this, always use parameterized queries or prepared statements to sanitize and validate user input before executing SQL queries.

// Example of using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Handle fetched data
}

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