About Lesson
Connecting to Database
Definition:
To work with databases in PHP, we need to connect to MySQL.
MySQLi (MySQL Improved) is an extension in PHP used to:
- Establish a connection with a MySQL database.
- Send SQL queries and get results.
- Work with procedural style or object-oriented style.
Procedural Connection:
PHP
<?php
$servername = "localhost"; // Server name where MySQL is running
$username = "root"; // Default MySQL username in local
$password = ""; // Password (empty for XAMPP/WAMP by default)
$dbname = "mydatabase"; // Database name
// Step 1: Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Step 2: Check connection
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Explanation:
mysqli_connect()
→ establishes connection to MySQL.- If the connection fails,
mysqli_connect_error()
shows the error. die()
stops the script execution and shows the error.- If successful, it prints
"Connected successfully"
.
Object-Oriented Connection:
PHP
<?php
$conn = new mysqli("localhost", "root", "", "mydatabase");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Explanation:
$conn = new mysqli(...)
→ creates a new object for the connection.$conn->connect_error
→ checks if there is any connection error.- This style is preferred in modern PHP applications.