The following code example shows Creating a Connection with MySQL Server Using PDO in PHP.
In order to create a connection with a MySQL database, we need to create an object of the PDO class. As can be seen in the code, the first parameter DSN (Data Source Name) specifies that the host is the localhost and given database. Afterward, the user and password are specified.
Significantly, the setAttribute() method we use here to set the attribute ATTR_ERRMODE (represents the error mode) to the value ERRMODE_EXCEPTION. Hence, it sets the error reporting mode to the exception. In other words, when a connection error occurs, an exception is thrown.
When there is no exception thrown, it means the connection with the database has been established successfully. Therefore, the corresponding message is displayed.
Program for Creating a Connection with MySQL Server Using PDO in PHP
connecting_database.php
<?php
$server='localhost';
$dbname='company';
$new_user='user_1';
$new_pass='123456';
try{
$con=new PDO("mysql:host=$server;dbname=$dbname", $new_user, $new_pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connection Established with Database!';
}
catch(PDOException $ex)
{
die('Error connecting with database: '.$ex->getMessage());
}
?>
Output

Once, the connection establishes, we can perform more operations on the database. For instance, we can create tables, insert records, display records, as well as update and delete records. When we write the PHP Script for other database operations on the specified database, we can include the above file using the require statement. For example, we need to include the statement require(‘connecting_database.php’); at the beginning of the PHP Script.
In order to find details on other database operations using PDO, click on the following links:
- Creating a Database table using PDO.
- Inserting Records
- Display Records
- Update and Delete
Since PDO supports not only the MySQL database, you can easily modify the code when you change the database. Moreover, PDO makes the code concise and helps in the ease of maintenance of the code.
Further Reading
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
PHP Projects for Undergraduate Students
Architectural Constraints of REST API
Creating a Classified Ads Application in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
