$db_username = "username"; $db_password = "password"; try { $pdo = new PDO('mysql:host=localhost;dbname=mydb', $db_username, $db_password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
$db_username = "username"; $db_password = "password"; $mysqli = new mysqli("localhost", $db_username, $db_password, "mydb"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); } else { echo "Connected successfully"; }In this example, we are using MySQLi to connect to a database and set the DB password using a variable. Package library used: PDO and MySQLi.