$host = "localhost";//Ip of database, in this case my host machine
$user = "root"; //Username to use
$pass = "qwerty";//Password for that user
$dbname = "DB";//Name of the database
try {
$connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo $e->getMessage();
}
//In this PHP DATA OBJECT (PDO) CONNECTION I am gonna use
//the exception code that will help hide your database login
//details from your users if there is an exception (error).
//dbname(database name)
//charset(characters encoding )
try {
$pdo = new PDO('mysql:host=localhost;dbname=joke;charset=utf8','username','password');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo 'Successfully Connected to the database';
} catch (PDOException $e) {
echo 'ErrorException'.$e->getMessage().'in'.$e->getFile().$e->getCode().$e->getLine();
}
const DB_HOST = 'localhost';
const DB_NAME = 'DB_Name'; //Name of the database
const DB_USERNAME = 'username'; //Username to use
const DB_PASSWORD = 'Password'; //Password for that user
// Data Source Name
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //make the default fetch be an anonymous object with column names as properties
];
//Create PDO instance
try {
$pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}