How to connect to a database

You can use PDO or mySQLi to connect to your database.

The syntax for creating an object from any class

new ClassName(arguments);

The syntax for creating a database object from the PDO class

new PDO($dsn, $username, $password);

The syntax for a DSN (Data Source Name) for a MySQL database

mysql:host=host_address;dbname=database_name

How to connect to a MySQL database named my_guitar_shop1

$dsn = "mysql:host=localhost;dbname=my_guitar_shop1";
$username = "mgs_user";
$password = "pa55word";
$db = new PDO($dsn, $username, $password); // creates PDO object 

How to connect to your MySQL database on bscacad3.buffalostate.edu using PDO

First, add these variables to your vars.php file:

$dbServer   = "bscacad3.buffalostate.edu";
$dbUsername = "your-buff-state-username";
$dbPassword = "your-Bannerid-beginning-with-a-CAPITAL-B";
$dbDatabase = "your-buff-state-username";

Add this to your functions.php file:

/*
 * Connect to a database using PDO
 * @param none
 * @return connection object
 */
function dbConnect() {
  global $debug, $dsn, $dbUsername, $dbPassword;
  try {
    $dbConn = new PDO($dsn, $dbUsername, $dbPassword);
    if ($debug) { echo("<p>Connection successful!</p>"); }
    return $dbConn;
  } catch (PDOException $e) {
    $error_message = $e->getMessage();
    echo("<p>Error message: $error_message;</p>");
    exit();
}

How to connect to your MySQL database on bscacad3.buffalostate.edu using mysqli()

Add this to your functions.php file:

/*
 * Connect to a database using mysqli
 * @param none
 * @return connection object
 */
function dbConnect() {
  global $debug, $dbServer, $dbUsername, $dbPassword, $dbDatabase;
  $dbConn = new mysqli();
  // try to make connection
  try {
    $dbConn->connect($dbServer, $dbUsername, $dbPassword, $dbDatabase);
    if ($debug) { echo("<p>Connection successful!</p>"); }
    return $dbConn;
  } catch (Exceptopn $exc) { 
    echo("<p>$exc: " . myError($dbConn->connect_error) . "</p>");
    exit;
  }
}

Description

Back