(PHP MySQL) Connect to a Database


The free MySQL database is very often used with PHP. Before you can access and work with data in a database, you must create a connection to the database. The example below performs the following tasks:
  1. Stores the connection in a variable ($conn) for later use in the script.
  2. The die part will be executed if the connection fails.
  3. The connection will be closed as soon as the script ends. To close the connection before, use the close function.
 <html><body>
 <?php
  $username = "wenchen";
  $database = "wenchen";
  $host     = "undcemmysql.mysql.database.azure.com";
  $password = "";

  // Initializing MySQLi
  $conn     = mysqli_init( );

  // Creating an SSL connection
  mysqli_ssl_set( $conn, NULL, NULL, "DigiCertGlobalRootCA.crt.pem", NULL, NULL );

  // Opening a new connection to the MySQL server
  mysqli_real_connect( $conn, $host, $username, $password, $database, 3306 );

  // Connecting to the database
  if ( $conn->connect_errno )
    die( 'Failed to connect to MySQL: ' . $conn->connect_error );
  else
    echo "Successfully connect to MySQL!";

  // Closing the database connection
  $conn->close( );
 ?>
 </body></html>
                   




      A virus walks into a bar.    
      The bartender says, "Sorry, I don’t serve viruses".    
      The virus turns him into the kind of bartender that does.