Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Database {
- /* Properties */
- private $conn;
- private $dsn = 'mysql:dbname=test;host=127.0.0.1';
- private $user = 'root';
- private $password = '';
- /* Creates database connection */
- public function __construct() {
- try {
- $this->conn = new PDO($this->dsn, $this->user, $this->password);
- } catch (PDOException $e) {
- print "Error!: " . $e->getMessage() . "";
- die();
- }
- return $this->conn;
- }
- }
- include "database.php";
- class User {
- /* Properties */
- private $conn;
- /* Get database access */
- public function __construct() {
- $this->conn = new Database();
- }
- /* Login a user */
- public function login() {
- $stmt = $this->conn->prepare("SELECT username, usermail FROM user");
- if($stmt->execute()) {
- while($rows = $stmt->fetch()) {
- $fetch[] = $rows;
- }
- return $fetch;
- }
- else {
- return false;
- }
- }
- }
- $user = new User();
- $list = $user->login();
- foreach($list as $test) {
- echo $test["username"];
- }
- <?php
- $host = '127.0.0.1';
- $db = 'test';
- $user = 'root';
- $pass = '';
- $charset = 'utf8';
- $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
- $opt = [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- PDO::ATTR_EMULATE_PREPARES => false,
- ];
- $pdo = new PDO($dsn, $user, $pass, $opt);
- <?php
- class User {
- /* Properties */
- private $conn;
- /* Get database access */
- public function __construct($pdo) {
- $this->conn = $pdo;
- }
- /* List all users */
- public function get_users() {
- return $this->conn->query("SELECT username, usermail FROM user")->fetchAll();
- }
- }
- include 'database.php';
- $user = new User($pdo);
- $list = $user->get_users();
- foreach($list as $test) {
- echo $test["username"];
- }
- username_foo
- username_bar
- username_baz
- <?php
- class Database {
- /* Properties */
- private $conn;
- private $dsn = 'mysql:dbname=test;host=127.0.0.1';
- private $user = 'root';
- private $password = '';
- /* Creates database connection */
- public function __construct() {
- }
- public function getConnection() {
- try {
- $this->conn = new PDO($this->dsn, $this->user, $this->password);
- } catch (PDOException $e) {
- print "Error!: " . $e->getMessage() . "";
- die();
- }
- return $this->conn;
- }
- }
- ?>
Add Comment
Please, Sign In to add comment