A
A
Alexander Vertelo2020-10-23 21:19:31
PHP
Alexander Vertelo, 2020-10-23 21:19:31

How to use PDO in other classes?

As I see it: I write a database connection class, I hook it up in the methods of other classes, and I'm already working there.
How I implement:

Connection class

class qpdo {
  public function __construct() {
    $host = 'localhost'; $port = '3306'; $base = 'cm'; $char = 'utf8';
    $dsn = 'mysql:host=' . $host . ';port=' . $port . ';dbname=' . $base . ';charset=' . $char . '';
    $user = 'root'; $pass = 'root';
    $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING];

      try                        {
      new PDO($dsn, $user, $pass, $opts);
    } catch(PDOexception $error) {
      echo 'Ошибка подключения к БД MySQL: ' . $error->getMessage() . ''; die;
    }
  }
}


Hacking in another class

class somethingClass {
  public $key

  function __construct() {
    $db = new qpdo();
  }

  function somethingFunction(string $key) {
    $query = $this->db->prepare("SELECT `key` FROM `table` WHERE `key` = :key");
    $query->execute(array(':key' => $key));
    $result = $query->fetch(PDO::FETCH_COLUMN);
    return $result;
  }
}



I receive:
Fatal error: Uncaught Error: Call to undefined method qpdo::prepare() in C:\OpenServer\domains\localhost\core.php:254 Stack trace: #0 C:\OpenServer\domains\localhost\app\index.php(18): somethingClass->somethingFunction() #1 {main} thrown in C:\OpenSerever\domains\localhost\core.php on line 254


I used to connect to the database simply, without using classes, and in each method of the classes in which you need to use the connection, global $qpdo;I wrote , but they say that this is shit code and wrong.

What to do, gentlemen?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-10-23
@FanatPHP

The question is good and correct. Everything else - not so much.
Unfortunately, what you have now is also govnokod and wrong.
Here you need to understand one very simple, but very unpleasant thing: OOP, unlike PHP, is a complex topic. By default, peeping there, copy-pasting here - OOP cannot be studied.
The maximum that you can do is the same procedure, side view. Unsupported shit code, just monkey-wrapped in classes.
But you still need to study.
The main thing to understand about OOP is that it is not about the classes themselves, but about their interaction .
that is why the same zhlobal is govnokodom. Because there is no interaction, and there is no class either - there is a function that if you take it out of the class, then NOTHING will change.
But what you have now is not OOP.
Each time you can create a new connection without any OOP. That's just it will kill you the database server.
To make it OOP, you need to pass an already created class instance for working with the database as a constructor parameter.
Besides, the qpdo class is some kind of anecdote, nonsense. The monkey saw a man wearing glasses, put a spoon on his nose and walks with a proud look. Outwardly, it looks the same, but it makes no sense.
Can you explain WHY you need the qpdo class? To register the settings? And you thought that the settings are DIFFERENT? That at home you have a root login and a password of emptiness, but this will not work on hosting. And what - will you rewrite the code, each time uploading it from home to the server? Seriously?
Settings should always lie separately. And you don't need your class for anything else.
Therefore,
1. throw qpdo in the trash, at least until you understand why you need your class and how to handle it.
2. Create once a class instance for working with the database (in the simplest case - PDO) and pass it to other classes through the constructor
3. In the constructor, assign it to a class variable that is used to access the database.
As a result, we return to the original question, how to pass the connection to another class:

class somethingClass {
  function __construct($db) {
    $this->db = $db;
  }

  function somethingFunction(string $key) {
    $query = $this->db->prepare("SELECT `key` FROM `table` WHERE `key` = :key");
    $query->execute(array(':key' => $key));
    return $query->fetchColumn();
  }
}

Bonus
echo 'Ошибка подключения к БД MySQL: ' . $error->getMessage() . ''; die;
- this is hell and govnokod.
Yes, it was written that way in the last century. It's been 20 damn years since then. 20 Carl! You probably weren't in the project yet.
A site that dumps all this on public display is a shame.
The site should always keep all errors to itself. And don't show it to anyone. And therefore, you never have to get your hands into the error that PHP throws out. We must let her go quietly where all the other mistakes go.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question