i want to make an backend application using php/pdo. I have found a lot different ways to do PDO connection strings. I was wondering, what is the best way to do a connection string using pdo. Is this the best way of doing a connection string or should i use some other code. Any suggestions or adjustments are welcome!
This is what i have at the moment:
<?php
$host = "localhost";
$db = "phpcrud";
$username = "root";
$password = "";
$conn = new PDO("mysql:host=$host;dbname=$db;charset=UTF8", $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
?>
This question is not as easy as it seems. I wrote a canonical example, How to connect to MySQL using PDO.
So let's see what can be improved here:
utf8
is only a limited subset)So here you go:
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new \PDO($dsn, $username, $password, $options);