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



     $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());


Creating a Connection with MySQL Server Using PDO in PHP
The Result of Creating a Connection with MySQL Server Using PDO in PHP

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:

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

Basic Programs 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

REST API Concepts

Creating a Classified Ads Application in PHP