1. Home
  2. Docs
  3. Web Technology II
  4. Working with Database
  5. Setting Up a Database Connection in PHP

Setting Up a Database Connection in PHP

PHP can connect to a variety of databases, but the most commonly used database with PHP is MySQL.

PHP provides two main extensions for database connection:

  • MySQLi (MySQL Improved)
  • PDO (PHP Data Objects)

Steps to Connect:

  • Specify database credentials: host, username, password, and database name.
  • Establish a connection using MySQLi or PDO.
  • Handle connection errors.

Example Code (MySQLi):

<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "my_database";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *