Doubt regarding php code for connecting to database

$mysql_link = mysql_connect("localhost", "username", "password") ;
mysql_select_db('MyDatabase') or die('Could not select database'); 

Now when I need to connect to my database, why do I write ‘localhost’ instead of ‘’?
Now if I decide to create a subdomain in my main domain and want to connect to a file in the subdomain, do I connect in the same manner above? ie I still write

$mysql_link = mysql_connect("localhost", 

and not

$mysql_link = mysql_connect("localhost/subdomain", 

If the web server and MySQL are on the same server then that is the ‘localhost’ (i.e. the local machine). Doesn’t matter if the web server is serving a sub domain.

You’d only use a domain or IP if MySQL is on a different server.

You connect to localhost (unless otherwise specified).

This is because MySQL runs as a service (It is separate from your domain name).
You also have an Apache service (This runs your webhost).

So if you have a webhost with lets say:

The above are setup to distribute your sites on top of the Apache service.
And you have one MySQL service running, so they would all go to that service, “localhost”.

Even though you can have many websites/subdomains on Apache (Virtual Hosts), it’s still one Apache Service running.

And even though you can have many databases inside MySQL, it’s one MySQL service running.

I hope that makes sense, best of luck.