Home >>MySQL Tutorial >PHP MySQL Connectivity
Use the mysql_connect( ) function to established connection to the MySQL server. To access the database functionality we have to make a connection to database using Php. mysql_connect() function is used to establish the connection to mysql server.
Four arguments need to be passed to mysql_connect() function.
Hostname : if you are working on local system , you can use localhost or you can also provide ip address or server name.mysql_connect(host, username, password, dbname);
Parameter | Description |
---|---|
host(Server name) | Either a host name(server name) or an IP address |
username | The MySQL user name |
password | The password to log in with |
dbname | Optional. The database to be used when performing queries |
Note : There are more available parameters, but the ones listed above are the most important. In the following example we store the connection in a variable ($con) for later use in the script
<?php // Create connection $con=mysql_connect("localhost","root","") or die(mysql_error()); ?>
Here localhost is server name. root is MySQL default user name. default password is blank and database name is my_db. mysql_error( ) function provides mysql connectivity error message.
<?php // Create connection $con=mysql_connect("localhost","root","","my_db") or die(mysql_error()); //code to be executed... // Close connection mysql_close($con); ?>
after work with the database is done we have to close the connection using mysql_close() function in which the connection to the database is passed.