Database Connectivity with MySQL in php
php can connect to MySQL databases to store, retrieve, update, and delete data. The two main approaches are PDO (php Data Objects) and MySQLi.
Connecting with PDO (Recommended)
PDO supports multiple databases and uses prepared statements by default:
<?php
$host = "localhost";
$dbname = "mydb";
$user = "root";
$pass = "secret";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>