Connect to the MySQL database
Create a connection to the MySQL database
When you can access the data in the database, you must create a connection to the database.
In PHP, this is similar to the mysql_connect () function.
Syntax
mysql_connect(servername,username,password);
Parameter |
Description |
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 "" |
Note: There are more available parameters, but the above list is the most important. Visit our full PHP MySQL reference for more details.
For example
In the following example, we store scripts connected to a variable ($ Control) for future use. The "dead" part will be killed if the connection fails:
<?php$con = mysql_connect("localhost","peter","abc123");if (!$con) { die('Could not connect: ' . mysql_error()); }
// some code
?>
Close connection
The purpose of the script when the connection is automatically closed. Before closing the connection, 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);?>