I am getting mysql_real_escape_string() function error while adding user?

The problem is from wp_insert_user and the fact that your value for user_pass is empty.

You should update your code as so

 $random_password = wp_generate_password(8,false);
 $user_data = array(
                'user_login' => $first_name,
                'user_pass' => $random_password,
                'user_email' => $trainer_email,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'role' => 'trainer'
            );

And remove this line wp_set_password($random_password, $user_id);

You should also check the value of your $user_id to make sure it’s not returning a WP_Error object
You can use var_dump($user_id')