If you want to build dynamic websites, establishing connection to database is one of the main task. In this article , we will provide you step-by-step guide for How to Connect to MySQL Database Using PHP in two different ways.
i).MySQLi extension
ii).PDO Method
Before connecting to database, first create the database.
Create Database connect to MySQL
Step 1- Open XAMPP
Step 2-Click on ‘Admin’ button as indicated against MySQL to open phpadmin panel.
Step 3: Click on ‘Databases‘ link to open window for listing existing databases and creating new database.
Step 4: Enter new database name ‘testDB‘ and charset and click ‘Create‘ button.
To connect to above database, we need to create a user for this. Lets create one database user for the same.
Create Database User connect to MySQL
Step 1 : Click on ‘User accounts‘ link.
Step 2- Click on ‘Add user account‘ link.
Step 3- Enter details as shown below and click on ‘Go‘ button at the bottom left of the page.
Connecting to Database-
Establish Database Connection
Method 1- MySQLi extension
MySQLi supports only MySQL database. The PHP code for connecting to a MySQL database using the MySQLi procedural approach is the following:
<?php
//Database Details
$hostName = "localhost";//If your database is on remote machine,replace localhost with IP Address
$DBname= "testdb";
$DBuser= "testuser";
$userPass= ""; //no password
// Create connection
$conn = mysqli_connect($hostName , $DBuser, $userPass, $DBname);
// Check connection
if ($conn->connect_error) {
die("Connection to mysql database failed: " . $conn->connect_error);
}
echo "Connect to mysql database established successfully!";
mysqli_close($conn);
?>
Method 2 : PDO
PDO stands for PHP Data Objects. Unlike mysqli which works only with MySQL database, PDO can work with any database. So, if you have to migrate your project to use another database, PDO makes the process easier by just changing connection string and some other queries. To use PDO in your PHP applications, PHP version must be 5.1 or higher.
<?php
//Database Details
$hostName = "localhost"; //If your database is on remote machine,replace localhost with IP Address
$DBname= "testdb";
$DBuser= "testuser";
$userPass= ""; //no password
try {
$conn = new PDO("mysql:host=$hostName ;dbname=$DBname", $DBuser, $userPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connect to mysql database established successfully";
} catch(PDOException $e) {
echo "Connection to mysql database failed: " . $e->getMessage();
}
?>
Also visit How to Install XAMPP on windows