1$host = "localhost";//Ip of database, in this case my host machine
2$user = "root"; //Username to use
3$pass = "qwerty";//Password for that user
4$dbname = "DB";//Name of the database
5
6try {
7 $connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
8 $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
9
10}catch(PDOException $e)
11{
12 echo $e->getMessage();
13}
1<?php
2$servername = "localhost";
3$username = "username";
4$password = "password";
5
6try {
7 $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
8 // set the PDO error mode to exception
9 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
10 echo "Connected successfully";
11} catch(PDOException $e) {
12 echo "Connection failed: " . $e->getMessage();
13}
14?>
1$host = '127.0.0.1';
2$db = 'test';
3$user = 'root';
4$pass = '';
5$charset = 'utf8mb4';
6$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
7$options = [
8 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
9 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
10 PDO::ATTR_EMULATE_PREPARES => false,];
11try {
12 $pdo = new PDO($dsn, $user, $pass, $options);
13} catch (\PDOException $e) {
14 throw new \PDOException($e->getMessage(), (int)$e->getCode());
15}
1const DB_HOST = 'localhost';
2const DB_NAME = 'DB_Name'; //Name of the database
3const DB_USERNAME = 'username'; //Username to use
4const DB_PASSWORD = 'Password'; //Password for that user
5
6
7// Data Source Name
8$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
9
10$options = [
11 PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
12 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
13 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //make the default fetch be an anonymous object with column names as properties
14];
15
16//Create PDO instance
17try {
18 $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
19} catch (PDOException $e) {
20 echo 'Connection failed: ' . $e->getMessage();
21}
1<?php
2
3$dsn = "mysql:host=localhost;dbname=mydb";
4$user = "user12";
5$passwd = "12user";
6
7$pdo = new PDO($dsn, $user, $passwd);
8
9
1<?php
2
3$dsn = "mysql:host=localhost;dbname=mydb";
4$user = "user12";
5$passwd = "12user";
6
7$pdo = new PDO($dsn, $user, $passwd);
8
9$stm = $pdo->query("SELECT * FROM countries");
10
11$rows = $stm->fetchAll(PDO::FETCH_NUM);
12
13foreach($rows as $row) {
14
15 printf("$row[0] $row[1] $row[2]\n");
16}
17