I am trying to connect mysql database using php. But it is running fine on local machine but not when hosted online and error appeared as mysqli_connect(): (HY000/2002): Co
I think you have to white list your hosting server's ip address to your DB server.
So your DB server will accept requests from your hosting server.
In my case, AWS firewall was blocking my web server.
Adding the web servers IP address to the firewall exceptions fixed this for me.
Your MySQL server is probably not configured to accept requests from the host you're trying to access it from.
Check the configuration for the server. Since you say the local machine can access it check where you permitted this and do the same for the ip of the online host.
If your website and MySQL database are hosted on separate servers, make sure that you've mentioned correct MySQL hostname (resolvable) in connection string.
In case you've specified the correct username, most probably your MySQL server isn't allowing remote MySQL connections from web server where you site resides. Contact your web hosting provider for the exact MySQL hostname and to allow your web server IP address for remote MySQL connections.