// using mysqli package library $host = 'localhost'; $username = 'root'; $password = 'password123'; $database = 'my_database'; $mysqli = mysqli_connect($host, $username, $password, $database);
// using PDO package library $host = 'localhost'; $username = 'root'; $password = 'password123'; $database = 'my_database'; $dsn = "mysql:host=$host;dbname=$database"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $pdo = new PDO($dsn, $username, $password, $options); } catch(PDOException $e) { echo $e->getMessage(); }In example 1, the mysqli package library is used to establish a connection with a MySQL database. The mysqli_connect function takes four parameters: host, username, password, and database name. The function returns a connection object that can be used to interact with the database. In example 2, the PDO package library is used to establish a connection with a MySQL database. The PDO constructor takes three parameters: Data Source Name (DSN), username, password, and an optional fourth parameter for additional configurations. The DSN contains information about the host, database name, and other driver-specific configurations. In this example, the ERRMODE_EXCEPTION attribute is set to ensure that exceptions are thrown in case of errors.