💡 What is Database Connectivity in PHP?
Database connectivity means connecting your PHP script with a database (like MySQL) to perform actions like Insert, Retrieve, Update, or Delete data using SQL.
PHP offers two main methods to connect with databases:
- MySQLi (MySQL Improved)
- PDO (PHP Data Objects)
✅ Database Connection using MySQLi (Procedural)
🔹 Step 1: Set Database Credentials
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
🔹 Step 2: Create Connection
$conn = mysqli_connect($servername, $username, $password, $database);
🔹 Step 3: Check Connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
✅ Full Working Example
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
✅ Database Connection using PDO
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
try {
// Create PDO connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set PDO error mode to Exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
📊 Comparison Table
Method | Description | Best Use |
---|---|---|
MySQLi | Works with MySQL only | Best for beginners and local projects |
PDO | Works with multiple DB types | Best for advanced and secure apps |
📌 What Can You Do After Connecting?
- INSERT data using SQL
- SELECT data to view records
- UPDATE data when needed
- DELETE unwanted data
0 Comments