How to Connect PHP to MySQL Database using PDO
Good day Everyone, Today I will show you How to Connect PHP to MySQL Database using PDO in a simple way. I believe that this tutorial will be beneficial for those who want to start learning PHP and PDO.
If you want to know more details about setting up a connection with PHP and MYSQL database. Please see this tutorial here Best MySQL Tutorial For Beginners in 7 Days.
Or you can directly start to manage the MySQL Database using this in-depth tutorial here MySQL Insert, Multiple Insert, and Last Inserted Query in PHP.
php to mysql pdo
Here’s the following code for connecting PHP to MySQL Database using PDO
<?php
$servername = "servername ";
$user = "user";
$password = "password";
try {
//setup database connection
$dbConn = new PDO("mysql:host=$servername ;dbname=test", $user, $password);
// set the PDO error mode to exception
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//display message if connected successfully
echo "Connected successfully";
}
catch(PDOException $e)
{
//display message if connection failed
echo "Connection failed: " . $e->getMessage();
}
?>Important reminders! You need to close the connection using this code:
$dbConn = null;
This is the code above when put this into real action.
<?php
$servername = "localhost";
$user = "user";
$password = "";
try {
//setup database connection
$dbConn = new PDO("mysql:host=".$servername.";dbname=test", $user, $password);
// set the PDO error mode to exception
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//display message if connected successfully
echo "Connected successfully";
}
catch(PDOException $e)
{
//display message if connection failed
echo "Connection failed: " . $e->getMessage();
}
?>
Recommended articles for you:
If you are looking for PHP Projects with a complete source, you can jump in here the best PHP Projects with source free to Download.
and if you want to design a database but don’t how, I have listed below the sample database design projects with complete documentation.
Sample Database Design With Documentation
- ER Diagram for Sales and Inventory System Database Design
- Ordering System Database Design with ERD
- ER Diagram for Water Refilling Station System Database Design
- Database Design for High School Enrollment System
If you have any questions or suggestions, please feel free to contact me on our contact page.
