What potential issues can arise when inserting data into a MySQL database using mysql_real_escape_string?

When inserting data into a MySQL database using mysql_real_escape_string, potential issues can arise if the database connection is not properly established or if the function is not used correctly. To solve this, ensure that the database connection is established before using mysql_real_escape_string and always apply the function to user input to prevent SQL injection attacks.

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

// Check if the connection is successful
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Use mysql_real_escape_string to escape user input before inserting into the database
$user_input = "user input here";
$escaped_input = mysqli_real_escape_string($connection, $user_input);

// Insert the escaped input into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_input')";
mysqli_query($connection, $query);

// Close the database connection
mysqli_close($connection);