Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Przejście z mysqli na PDO
Marci88
post 6.06.2019, 15:54:57
Post #1





Grupa: Zarejestrowani
Postów: 4
Pomógł: 0
Dołączył: 6.06.2019

Ostrzeżenie: (0%)
-----


Dzień dobry.
Aby się rozwijać postanowiłem nauczyć się i przejść na PDO. Jednak tu trochę inaczej sprawa wygląda przez bindowanie chociażby. Będę wdzięczny, jeśli ktoś pomoże łatwo ten temat ogarnąć. Otóż wypadało by mieć bazę w klasie, więc odpada załączanie pliku z z PDO i takie korzystanie, prawda?

Do tej pory, korzystając z MySQL, zrobiłem sobie coś w tym stylu:

  1. <?PHP
  2. class database{
  3. private $db;
  4.  
  5. public function __construct($config){
  6. $this->config = $config;
  7.  
  8. if($this->config['db_active'] == false){
  9. die("Database is not activated");
  10. }
  11.  
  12. $this->db = new mysqli($this->config['db_host'], $this->config['db_user'], $this->config['db_password'], $this->config['db_database']);
  13.  
  14. if($this->db->connect_error){
  15. die("Connection failed: " . $this->db->connect_error);
  16. }
  17. }
  18. public function queryFetch($query){
  19. $result = mysqli_fetch_array(mysqli_query($this->db, $query));
  20.  
  21. if($this->db->error && $this->config['db_debug_mode']){
  22. die("Error description: " . $this->db->error);
  23. }
  24.  
  25. return $result;
  26. }
  27. public function queryNum($query){
  28. $result = mysqli_num_rows(mysqli_query($this->db, $query));
  29.  
  30. if($this->db->error && $this->config['db_debug_mode']){
  31. die("Error description: " . $this->db->error);
  32. }
  33.  
  34. return $result;
  35. }
  36. public function query($query){
  37. $result = mysqli_query($this->db, $query);
  38.  
  39. if($this->db->error && $this->config['db_debug_mode']){
  40. die("Error description: " . $this->db->error);
  41. }
  42.  
  43. return $result;
  44. }
  45. }


A jeśli chodzi o PDO, to jakoś tak miałoby to wyglądać? Czy to jest poprawnie?
  1. class Database
  2. {
  3. public function __construct($config)
  4. {
  5. $this->config = $config;
  6.  
  7. $dsn = "mysql:host={$config['db_host']};dbname={$config['db_database']};charset={$config['db_charset']}";
  8.  
  9. try {
  10. $pdo = new PDO($dsn, $config['db_user'], $config['db_password'], $config['db_options']);
  11. $this->pdo = $pdo;
  12. } catch (\PDOException $e) {
  13. throw new \PDOException($e->getMessage(), (int)$e->getCode());
  14. }
  15. }
  16.  
  17. public function query($query)
  18. {
  19. $stmp = $this->pdo->query($query);
  20. return $stmp;
  21. }
  22.  
  23. public function prepare($query)
  24. {
  25. $stmp = $this->pdo->prepare($query);
  26. $stmp->execute(['id' => 5]);
  27. return $stmp;
  28. }
  29. }
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 19.04.2024 - 08:05