Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write an example to establish MySQL database connection using PHP script?
In PHP, you can establish a MySQL database connection using MySQLi or PDO extensions. The old mysql_connect() function is deprecated and should be avoided. Here are modern approaches to connect to MySQL database.
Using MySQLi (Procedural)
The MySQLi extension provides an interface to access MySQL databases −
<?php
$servername = "localhost";
$username = "guest";
$password = "guest123";
$database = "testdb";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// Close connection
mysqli_close($conn);
?>
Using MySQLi (Object-Oriented)
The object-oriented approach provides better code organization −
<?php
$servername = "localhost";
$username = "guest";
$password = "guest123";
$database = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Close connection
$conn->close();
?>
Using PDO
PDO (PHP Data Objects) provides a database-agnostic interface −
<?php
$servername = "localhost";
$username = "guest";
$password = "guest123";
$database = "testdb";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Connection closes automatically when script ends
?>
Comparison
| Method | Object-Oriented | Prepared Statements | Database Support |
|---|---|---|---|
| MySQLi Procedural | No | Yes | MySQL only |
| MySQLi OOP | Yes | Yes | MySQL only |
| PDO | Yes | Yes | Multiple databases |
Conclusion
Use MySQLi for MySQL-specific applications and PDO for database-agnostic code. Always use prepared statements for user input to prevent SQL injection attacks.
Advertisements
