PHP Designing Interfaces in PHP Introducing Interfaces Implement MySQL RepositoryInterface

Zdenek Krcal
Zdenek Krcal
48,673 Points

How can I use mysql connection when I don't know username, password and server for connection?

Im doing excercise in PHP interfaces and I don't know ho to connect to mysql when I don't know credentials.

sqlRepository.php
<?php

class sqlRepository extends PDO implements RepositoryInterface
{
  /*const USERNAME="root";
        const PASSWORD="";
        const HOST="localhost";
        const DB="parcial";

        private function getConnection(){
            $username = self::USERNAME;
            $password = self::PASSWORD;
            $host = self::HOST;
            $db = self::DB;
            $connection = new PDO("mysql:dbname=$db;host=$host", $username, $password);
            return $connection;
        }*/


  public function all($entity)
  {
    //$connection = $this->getConnection();
    $results = $database->query("SELECT * FROM $entity");
    return $results->fetchAll(PDO::FETCH_OBJ);
  }

}

2 Answers

Daryl Peterson
Daryl Peterson
7,811 Points

The exercise uses a sqlite database. It's designed to to follow the jsonRepository class

Here's what I ended up using class sqlRepository extends PDO implements RepositoryInterface { protected $file;

public function __construct($file)
{

    $this->file = $file;
    $file_name  = str_replace("sqlite:", '', $file);

    if (!file_exists($file_name)) {
        die('Invalid sqlite file: '.$file_name);
    }

    try {
        parent::__construct($file);
    } catch (PDOException $e) {
        die($e->getMessage());
    }
}

public function all($entity)
{


    $sql  = "SELECT * FROM $entity";
    $stmt = $this->query($sql);
    return $stmt->fetchAll(PDO::FETCH_OBJ);
}

public function find($entity, $value, $field = 'id')
{
    $sql  = "SELECT * FROM $entity WHERE $field = :value";
    $stmt = $this->prepare($sql);
    $stmt->bindParam(':value', $value, PDO::PARAM_STR);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_OBJ);

}

}

Lorenzo Leva
Lorenzo Leva
12,262 Points

Hi, I’m sorry but you need a server to connect to because you need a database where you store your info. It’s like php is the wheel and the database is the car. So that means that you have to install an MySQL serve on your mashine. (Or every other database) It’s pretty easy just go to the MySQL site and download the downloader. Then there is a step by step instruction. I would suggest that you download also workbench so you can set up your server easier. If you have any trouble just replay and I will help you. Have a nice day.