DEV Community

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

Posted on

1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
reacthunter0324 profile image
React Hunter

:)
It's too basic code

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post