PHP and MySQL Introduction

MySQL is a database that can be used in conjunction with PHP to make websites more dynamic. It can be used to store content and configuration information. MySQL is one of a number of databases that can be used with Content Management Systems such as Drupal, Joomla and WordPress.

Connecting to a MySQL Database

In order to access a MySQL database with PHP, to either select, insert, update or delete data, you first need to connect to the database. Below is an example of how this can be achieved.

<?php

   // Create variables.
   $servername = "localhost";
   $database = "testDB";
   $username = "testUN";
   $password = "testPW";

   // Try to connect to the database.
   try {

      $connect = new PDO("mysql:host=$servername;dbname=$database;",$username,$password);

      // Set the error mode so that exceptions are thrown when SQL statements are executed.
      $connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

   } catch (Exception $e) {

      // If connection fails, display an error and exit.
      echo "Could not connect to the database.";
      exit;

   }
   
   // Display connection successful message.
   echo "Connected to database.";

?>

In this example, a 'try-catch' block is used to catch any exceptions. A 'try-catch' block allows you to handle exceptions in a user-friendly way. In this instance, it will try to connect to the database and if it fails an error message will be displayed. Note the 'exit' command after the displaying of the error message. This basically stops the execution of the PHP script, so the message about connecting to the database successfully will not be displayed if the connection fails.