Created
March 17, 2019 11:56
-
-
Save anaelleltd/eb633bc274b876bde4e6f811321301c2 to your computer and use it in GitHub Desktop.
PDO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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