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. In PHP, this is done with the mysqli function.

mysqli( servername, username, password );

Parameter Description
servername Specifies the server to connect to.
username Specifies the username to log in with.
password Specifies the password to log in with.

There are more available parameters, but the ones listed above are the most important. 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
  $servername = "undcsmysql.mysql.database.azure.com";
  $username   = "wenchen@undcsmysql";
  $password   = "";
  $conn       = new mysqli( $servername, $username, $password );

  if ( $conn->connect_error( ) )
    die( 'Could not connect: ' . $conn->connect_error );
  else {
    echo "Successfully connect to MySQL!";
    // Close the database.
    $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.