+ 7
How can I connect to a MySQL database from a PHP script ?
5 Answers
+ 11
Using mysqli:
$connection = mysqli_connect(localhost, username, password, database_name);
Now you can use $connection everytime you want to manipulate SQL.
+ 1
Use PDO:
$host = 'localhost';
$db = 'test';
$user = 'root';
$pass = 'yourpassword';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
More info: https://phpdelusions.net/pdo
+ 1
Using mysqli:
$connection = mysqli_connect(localhost, username, password, database_name);
Now you can use $connection everytime you want to manipulate SQL.
(copied Dominoâs answer for corrections)
if you want to include this connection in all pages its advisable to have it in one page and use php includes to import it into any page or if you have a universal header you can include it their, always have a function page just incase you wanna edit, you edit in only one oage rather that all pages.