PHP MySQL Connect to a Database
The free MySQL database is very often used with PHP.
Before you can access and work with data in a database, you must create a connection to the database.
In PHP, this is done with the mysqli
class.
$conn = new mysqli( servername, username, password, schema );
|
Parameter |
Description |
servername |
Specifies the server to connect to. |
username |
Specifies the username to log in with. |
password |
Specifies the password to log in with. |
schema |
Specifies the database to use. |
There are more available parameters, but the ones listed above are the most important.
The example below performs the following tasks:
- Stores the connection in an object (
$conn
) for later use in the script.
- The
die
part will be executed if the connection fails.
- The connection will be closed as soon as the script ends.
To close the connection before, use the
close( )
function.