Database Connectivity in PHP
Connecting to and interacting with databases using PHP is a common task in web development. PHP provides several extensions and libraries for this purpose, with MySQLi and PDO being the most popular choices. Below, I'll explain how to connect to a database and perform basic database operations using both MySQLi and PDO extensions.
MySQLi Extension:
Connect to the Database:
To connect to a MySQL database using MySQLi, you can use the following code:
php code
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Perform Database Operations:
After establishing a connection, you can perform various database operations like querying, inserting, updating, and deleting data. Here's an example of querying data:
php code
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
Close the Connection:
Always remember to close the database connection when you're done with it:
php code
$conn->close();
PDO (PHP Data Objects):
Connect to the Database:
To connect to a database using PDO, you need to create a connection using the following code:
php code
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
Perform Database Operations:
You can execute SQL statements using PDO prepared statements. Here's an example of querying data:
php code
$sql = "SELECT * FROM your_table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
Close the Connection:
PDO automatically closes the connection when the object is destroyed or when the script finishes execution. However, it's still good practice to explicitly close it if needed:
php code
$conn = null; // Closes the connection
Both MySQLi and PDO are powerful tools for database connectivity in PHP. The choice between them often depends on your project requirements and personal preferences. PDO is more flexible and works with various database systems, while MySQLi is specific to MySQL but provides some additional features for MySQL-specific functionality.
Comments
Post a Comment