What potential security risks are involved in executing PHP MySQL commands based on user input, such as in the case of a chat function?

Executing PHP MySQL commands based on user input can lead to SQL injection attacks, where malicious code is injected into the SQL query. To prevent this, it is important to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separates the SQL query from the user input.

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

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

// Sanitize user input
$user_input = $mysqli->real_escape_string($_POST['user_input']);

// Prepare SQL statement with parameterized query
$stmt = $mysqli->prepare("SELECT * FROM chat_messages WHERE message = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
$result = $stmt->get_result();

// Process query results
while ($row = $result->fetch_assoc()) {
    // Output chat messages
}

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