|
Before using MySQL or any other database, we need to connect to it first (establish connection).
we will use php+MySQL in this example
There are two functions available in PHP:
1. mysql_connect() mysql_connect(servername,username,password);
- servername - (Optional) Specifies the server to connect to. Default value is "localhost:3306".
- username - (Optional) Specifies the username to log in with. Default value is the name of the user that owns the server process.
- password - (Optional) Specifies the password to log in with. Default is "" (empty string).
Of course there are more parameters, but here listed are the ones that are used in everyday programmers life, so we will be looking at those listed above only.
If the connection was successful we have variable "$con" set to a connection identifier and can use in the later script execution, and connection closing. If the connection can't be established then "die" will print the error and stop execution of the script.
When issuing mysql_connect() we may need to close connection when finished our queries to the database, this is not necessary as non-persistent open links are automatically closed at the end of the script's execution. To close connection we issue: mysql_close($con);
That's it!
Now le's go to the second type of the connection: 2. mysql_pconnect() - a persistent connection to a MySQL database server. mysql_pconnect(servername,username,password);
There are more variables as in the example above, but we will use the simple connection, to get You started. It is very much like mysql_connect() with two major differencies: - When connecting this function will first look for already open connections with the host/username/password given, if theer is one, then it will use that connections identifier instead of opening new connection.
- When script execution ends, the connection to MySQL will not be closed, and be used for future connections. Also this type of connection can't be closed by mysql_close() (that's why this connection type is called "persistant" - mysql_pconnect() )
Usefull information: To tell mysql_connect() or mysql_pconnect() to connect to mysql on a port other than the default, use a colon, like in this example: mysql_connect("localhost:1337", "username", "password");
would connect to localhost on port 1337 I hope this information will give you the clue how to establish PHP->MySQL connection.
Good Luck!
|