PHP Database(MySql) Connection

Connecting PHP to a database is a common task, and it’s typically done using the PDO (PHP Data Objects) extension or MySQLi (MySQL Improved) extension. I’ll provide examples for both PDO and MySQLi.

Using PDO:

<?php
$host = "your_database_host";
$dbname = "your_database_name";
$username = "your_username";
$password = "your_password";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Replace “your_database_host,” “your_database_name,” “your_username,” and “your_password” with your actual database details.

Using MySQLi:

<?php
$host = "your_database_host";
$dbname = "your_database_name";
$username = "your_username";
$password = "your_password";

$conn = new mysqli($host, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
$conn->close();
?>

Replace “your_database_host,” “your_database_name,” “your_username,” and “your_password” with your actual database details.

Choose the method that suits your needs or is consistent with your project’s requirements. If you have a specific database type (e.g., MySQL, PostgreSQL), make sure to adjust the connection details accordingly. Additionally, consider using environment variables or a configuration file to store sensitive information like database credentials for security purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *