How to connect to a mysql database using php?

Connecting to a MySQL database is a common task when developing PHP applications. The MySQLi or PDO extension can be used for this purpose.


  $server = 'localhost';
  $username = 'username';
  $password = 'password';
  $database = 'database';
  $conn = new mysqli($server, $username, $password, $database);
  

Ensure that you handle connection errors and close the connection after using it. For instance:


  if ($conn->connect_error) {
      die('Connection failed: ' . $conn->connect_error);
  } 
  $conn->close();
  

Beginner's Guide to PHP