Skip to content

Instantly share code, notes, and snippets.

@anaelleltd
Created March 17, 2019 11:56
Show Gist options
  • Save anaelleltd/eb633bc274b876bde4e6f811321301c2 to your computer and use it in GitHub Desktop.
Save anaelleltd/eb633bc274b876bde4e6f811321301c2 to your computer and use it in GitHub Desktop.
PDO
Task:
Use PDO to establish a connection to a MySQL server
Catch an exception with a try-catch statement
Use the exit function
Configure PDO for exception by calling the PDO object’s setAttribute method - p103 of text
Configure character encoding utf8
Set the output to say 'Unable to connect to the database server.' If cannot connect. And include the error message.
Set the output to say 'Database connection established.'
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "mycompany";
try
{
$DBcon = new PDO("mysql:host={$DB_host};dbname={$DB_name};charset=utf8",$DB_user,$DB_pass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo '<p id="dbmycompanyconnection">Database connection established.</p>';
}
catch(PDOException $e)
{echo '<p id="dbmycompanyfailure">Unable to connect to the database server!</p>'.$e->getMessage(). "<br/>";
exit();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment