Connecting to a MySQL database in PHP can be done using either the PDO (PHP Data Objects) or MySQLi (MySQL Improved) extension. Both extensions provide a way to interact with your database, but they have different features and advantages.
PDO offers a data-access abstraction layer, which means you can use the same functions to interact with different types of databases. Here’s how you can connect to a MySQL database using PDO:
<?php
// Database configurations
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
echo "Connected to the database successfully!";
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
MySQLi is specific to MySQL and offers both procedural and object-oriented approaches. Here’s how to connect to a MySQL database using MySQLi:
<?php
// Database configurations
$host = 'localhost';
$user = 'your_username';
$pass = 'your_password';
$db = 'your_database';
// Create connection
$mysqli = new mysqli($host, $user, $pass, $db);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected to the database successfully!";
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?