CBD
Normal
<?php
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "University";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
// Close connection
$conn->close();
?>
PDO
<?php
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "University";
try {
// PDO connection
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set PDO to throw exceptions on error
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Object Oriented
<?php
class Database {
private $servername = "localhost"; // Change this to your MySQL server hostname if it's different
private $username = "your_username"; // Replace 'your_username' with your actual MySQL username
private $password = "your_password"; // Replace 'your_password' with your actual MySQL password
private $database = "University"; // Replace 'University' with your actual database name
private $conn;
// Constructor to establish connection
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->database", $this->username, $this->password);
// Set PDO to throw exceptions on error
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
// Method to get the connection object
public function getConnection() {
return $this->conn;
}
// Destructor to close connection when object is destroyed
public function __destruct() {
$this->conn = null;
}
}
// Usage
$database = new Database();
$conn = $database->getConnection();
?>