PHP MySQL: Connecting to MySQL Database?
Summary: in this tutorial, we will show you how to connect to MySQL database server using PDO object.
Before connecting to a MySQL database, you have to specify the following information:
- MySQL data source name or
DSN
: specifies the address of the MySQL database server. You can use IP address or server name e.g.,127.0.0.1
orlocalhost
- MySQL database name: indicates the name of the database that you want to connect to.
- Username and password: specify username and password of the MySQL’s user that you use to connect to the MySQL database server. The account must have sufficient privileges to access the database specified above.
We will use:
- The local MySQL database server so the
DSN
islocalhost
. - The
classicmodels
as the sample database. - The
root
account with a blank password, just for the sake of demonstration.
Connecting to MySQL steps
First, to make it convenient, we will create a new PHP file for database configuration named
dbconfig.php
that holds all configured parameters:
Second, we create a new PHP file named
phpmysqlconnect.php
:
How the script works.
- We included the
dbconfig.php
file into the script by using therequire_once
function. - Inside the
try
block, we created a new PDO object with three arguments: connection string, username, and password. The connection string is composed of$host
and$dbname
variables in thedbconfig.php
file. - If the connection to the MySQL database established successfully, we displayed a success message. If there was any errors or exceptions, PHP issued a
PDOException
that contains the detailed error message. We call thegetMesage()
method of thePDOException
object to get the detailed message for displaying.
Third, let’s test the script from the web browser.
It works as expected. We’ve successfully connected to the MySQL server.
Let’s try to change something in the code to make the script display an error message. If you set the
$username
variable to blank, you will get the following error message:
The error message says that:
Because we don’t have any blank user in the
classicmodels
database.
When the script ends, PHP automatically closes the connection to the MySQL database server. If you want to close the database connection explicitly, you need to set the PDO object to
null
as follows:
You can download the scripts of this tutorial via the following download link:
[download id=”6590″]
In this tutorial, you’ve learned how to connect to MySQL using PHP PDO object and handle any exception that may occur when connecting the MySQL database.
0 comments:
Post a Comment