PHP MySQL Database Connection
- Previous Page MySQL Introduction
- Next Page MySQL Create
Free MySQL databases are usually accessed through PHP.
Connecting to a MySQL Database
Before you can access and process data in the database, you must create a connection to the database.
In PHP, this task is completed through the mysql_connect() function.
Syntax
mysql_connect(servername,username,password);
Parameter | Description |
---|---|
servername | Optional. Specifies the server to connect to. The default is "localhost:3306". |
username | Optional. Specifies the username used for login. The default value is the name of the user owning the server process. |
password | Optional. Specifies the password used for login. The default is "". |
Note:Although there are other parameters, the most important ones are listed above. Please visit the reference provided by CodeW3C.com PHP MySQL Reference Manualfor more detailed information.
Example
In the following example, we store the connection used in the script in a variable ($con) for later use. If the connection fails, the 'die' part will be executed:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
Close Connection
When the script ends, the connection will be closed. If you need to close the connection early, please use the mysql_close() function.
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>
- Previous Page MySQL Introduction
- Next Page MySQL Create