Last active
January 5, 2024 00:57
-
-
Save susanBuck/f5274cdea2ed8ff4cf203cca884fe7b4 to your computer and use it in GitHub Desktop.
PHP database connection test
This file contains hidden or 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
<?php | |
# Basic PHP code to test a connection with a MySQL database | |
# https://codewithsusan.com | |
# https://www.youtube.com/channel/UCLyz8iEvzxyhKEBzOTs6bJQ | |
# Set up all the variables we need to make a connection | |
$host = '127.0.0.1'; # Common hosts for local servers include '127.0.0.1' or 'localhost' | |
$database = 'demo'; | |
$username = 'root'; | |
$password = ''; | |
# DSN (Data Source Name) string | |
# contains the information required to connect to the database | |
$dsn = "mysql:host=$host;dbname=$database;charset=utf8mb4;port=3307"; | |
# Driver-specific connection options | |
$options = [ | |
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, | |
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, | |
\PDO::ATTR_EMULATE_PREPARES => false, | |
]; | |
try { | |
# Create a PDO instance representing a connection to a database | |
$pdo = new \PDO($dsn, $username, $password, $options); | |
} catch (\PDOException $e) { | |
# If the connection fails, details will be output | |
throw new \PDOException($e->getMessage(), (int) $e->getCode()); | |
} | |
# If an exception was not thrown, we can assume the connection was successful | |
echo 'Connection successful'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment