DEV Community

Cover image for How to Connect Database in PHP?
TechzPad
TechzPad

Posted on

How to Connect Database in PHP?

To connect the database in PHP, you will need to use the MySQLi (MySQL Improved) or PDO (PHP Data Objects) extension. Both of these extensions provide an object-oriented interface for interacting with a MySQL database.
Here is an example of how to connect to a MySQL database using the MySQLi extension:

`<?php
$servername = "hostname";
$username = "username";
$password = "password";
$dbname = "database name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>`
Please make sure to replace the placeholders (hostname, username, password, and database name) with the appropriate values for your database. It’s important to also make sure that you have the correct driver installed to connect to the database.

Top comments (1)

Collapse
 
reacthunter0324 profile image
React Hunter

:)
It's too basic code