How to restrict access to specific php file to only athenticated users
.htaccess won't help with this; Apache doesn't know what an authenticated Drupal user is, and there's no easy way to grant it that knowledge. Fortunately there's a much better option:
Create a route in a custom module, and execute your code in its controller. You can easily protect the route with permissions, or by role. Aside from the flexibility this gives you around access control, you can also refactor your custom DB code to use Drupal's database API, making your code more future-proof.
The other option, less desirable IMO for your requirements, is to bootstrap Drupal in your custom PHP file, and use the current_user service to determine whether the user has access to your script.