L
L
lexstile2020-04-17 22:43:07
PHP
lexstile, 2020-04-17 22:43:07

How can I work with db class in any file?

There is a small class (file: db.php):

spoiler
class Db {

  protected $db;
  
  public function __construct() {
    $config = require 'config.php';
    $this->db = new PDO('mysql:host='.$config['host'].';charset=utf8;dbname='.$config['name'].'', $config['user'], $config['password']);
  }

  public function query($sql, $params = []) {
    echo '<pre>' . print_r($sql,true) . '</pre>';
    exit;
    $stmt = $this->db->prepare($sql);
    if (!empty($params)) {
      foreach ($params as $key => $val) {
        if (is_int($val)) {
          $type = PDO::PARAM_INT;
        } else {
          $type = PDO::PARAM_STR;
        }
        $stmt->bindValue(':'.$key, $val, $type);
      }
    }
    $stmt->execute();
    return $stmt;
  }

  public function row($sql, $params = []) {
    $result = $this->query($sql, $params);
    return $result->fetchAll(PDO::FETCH_ASSOC);
  }

  public function column($sql, $params = []) {
    $result = $this->query($sql, $params);
    return $result->fetchColumn();
  }

  public function lastInsertId() {
    return $this->db->lastInsertId();
  }

}

I try to connect in my file (does not work):
spoiler
include 'Db.php';

$DB = new Db;

addUser(123, 111111111);

function addUser($user_id, $date) {
  $params = [
    'user_id' => $user_id,
    'date' => $date,
  ];
  $DB->query('INSERT INTO users (user_id, date) VALUES (:name, :date)', $params);
  return $DB->lastInsertId();
}


Ошибка: Fatal error: Uncaught Error: Call to a member function query() on null

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2020-04-18
@lexstile

The idea is good, but the execution is not so good.
Let's start with the fact that this is a very illogical class.
How to use it at all if the row() function returns not one row, but all?
There is a lot of extra code in the class, but at the same time, 90% of the PDO functionality is simply not available in it
. The class should be rewritten at least like this:

class Db {
    public $db;
 
    public function __construct() {
        $config = require __DIR__.'/config.php'; 
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];
        $dsn = 'mysql:host='.$config['host'].';charset=utf8;dbname='.$config['name'];
        $this->db = new PDO($dsn, $config['user'], $config['password'], $options);
    }
    public function query($sql, $params = []) {
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
    public function cell($sql, $params = []) {
        return $this->query($sql, $params)->fetchColumn();
    }
    public function row($sql, $params = [], $mode=PDO::FETCH_ASSOC) {
        return $this->query($sql, $params)->fetch($mode);
    }
    public function all($sql, $params = [], $mode=PDO::FETCH_ASSOC) {
        return $this->query($sql, $params)->fetchAll($mode);
    }
    public function column($sql, $params = []) {
        return $this->query($sql, $params)->fetchAll(PDO::FETCH_COLUMN);
    }
    public function lastInsertId() {
       return $this->db->lastInsertId();
    }
}

once ALL PDO functionality has been added, it will be possible to make the db private again. Until then, call the missing PDO functions through it.
And connecting an object of this class is easier than a steamed turnip: just pass it into a function
include 'Db.php';
$db = new Db;

addUser($db, 123, 111111111);

function addUser($db, $user_id, $date) {
  $params = [
    'user_id' => $user_id,
    'date' => $date,
  ];
  $db->query('INSERT INTO users (user_id, date) VALUES (:name, :date)', $params);
  return $db->lastInsertId();
}

A
Alexander Shvedov, 2020-04-17
@constintmid

do require 'Db.php'
and do new Db()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question