Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [php][mysql] Klasa do obsługi baz danych.
Maciekbjw
post 2.03.2008, 21:27:17
Post #1





Grupa: Zarejestrowani
Postów: 217
Pomógł: 23
Dołączył: 2.12.2007
Skąd: Warszawa

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


Witam, zacząłem pisać sobie prostą klasę do obsługi baz danych. Zawierać będzie podstawowe funkcje, czyli łączenie, rozłaczanie, dodawanie, edycję i kasowanie rekordów. Mam już początek i chciałbym spytać Was, może bardziej doświadczonych, czy idę w dobrym kierunku i czy takie pisanie jest poprawne. Byłbym wdzięczny za jakieś opinie i uwagi.

Oto kod:

Kod
class MySQL {


  private


  $type, #typ

  $host,  #host

  $user,  #uzytkownik

  $name,  #nazwa bazy

  $password, #haslo do bazy
  
  $connection; #uchwyt do polaczenia
  
  
  public
  
  $active, #uchwyt do akutalnego zapytania
  
  $time, #czas wykonania zapytan
  
  $count, #ilosc zapytan
  
  $error; #ewentualne bledy
  
  
  #konstruktor klasy MySQL
function __construct() {


require_once('db-config.php')
or die('Error, file not found!');

$this->type = $type;
$this->host = $host;
$this->user = $user;
$this->name = $name;
$this->password = $password;
$this->count = 0;

if(!isset($this->connection)) {
$this->Connect();

}
}
#laczy sie z baza danych
function Connect() {
$this->connection = mysql_connect('$this->host','$this->name','$this->user','$this->password')
or die ('Error!');


}
#rozlacza sie z baza danych
function Disconnect() {


mysql_close($this->connection);

}
#w razie niepowodzenia wywala blad
function Error(){

$this->error = mysql_error();


}
} #end class


--------------------
Masz swoje mieszkanie i chcesz je wynająć? Sprawdź ofertę Zarzadządzanie Najmem

WRONA.IT - pozycjonowanie stron
www.ecyklopedia.pl
Go to the top of the page
+Quote Post
phpion
post 2.03.2008, 21:39:57
Post #2





Grupa: Moderatorzy
Postów: 6 072
Pomógł: 861
Dołączył: 10.12.2003
Skąd: Dąbrowa Górnicza




Oto moje uwagi:
1. Zamiast "private $pole1, pole2;" wypisywać każde osobno tj. "private $pole1; private $pole2;"
2. Przyjęło się poprzedzać nazwy prywatnych składowych podkreśleniem tj. "private $_pole1;"
3. Przyjęło się nazwy metod/pól rozpoczynać małą literą.
4. W konstruktorze klasy możesz jako opcjonalny parametr podawać ścieżkę do pliku z configiem, a jeśli takowa nie zostanie podana to próbujesz wczytać domyślny plik.
5. Komentarze pisz w stylu phpdoc.
6a. Działa ci twój kod? Konkretnie chodzi mi o:
  1. <?php
  2. $this->connection = mysql_connect('$this->host','$this->name','$this->user','$this->password') or die ('Error!');
  3. ?>

według mojej wiedzy to nie ma prawa działać (wywal te ' w mysql_connect()).
6b. Czy aby nie masz za dużo parametrów w mysql_connect()? Zobacz jakie parametry powinna przyjmować funkcja mysql_connect" title="Zobacz w manualu PHP" target="_manual.
7. Szkoda, że klasa nie robi nic poza nawiązywaniem i kończeniem połączenia z bazą...

Ten post edytował phpion 2.03.2008, 21:42:11
Go to the top of the page
+Quote Post
Maciekbjw
post 2.03.2008, 21:44:38
Post #3





Grupa: Zarejestrowani
Postów: 217
Pomógł: 23
Dołączył: 2.12.2007
Skąd: Warszawa

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


Dzięki wielkie za rady... postaram się wszystko poprawić!

ad.7 Zaraz zacznę pisać większą funkcjonalność, tylko chciałem się upewnić czy dobrze piszę, żeby później nie było dużo poprawiania. Dzięki jeszcze raz, pozdrawiam!


--------------------
Masz swoje mieszkanie i chcesz je wynająć? Sprawdź ofertę Zarzadządzanie Najmem

WRONA.IT - pozycjonowanie stron
www.ecyklopedia.pl
Go to the top of the page
+Quote Post
matix
post 2.03.2008, 22:09:27
Post #4





Grupa: Zarejestrowani
Postów: 278
Pomógł: 10
Dołączył: 13.02.2007
Skąd: Rybnik

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


Przede wszystkim jeśli tworzysz klase do obsługi bazy danych to tylko po to, żeby sobie uprościć zapytania, zaoszczędzić tego żmudnego łączenia itp.

Przedstawiam moją klasę bazy danych. Piszę na niej od roku i jest wszystko gitara winksmiley.jpg

  1. <?
  2. class db {
  3. private $_Conn, $_rLast, $_sLast, $_aAttributes, $_sMethod;
  4.  
  5. public function __construct($connection = '')
  6. {
  7. $oConfig = new config('database');
  8.  
  9. $sDefault = $oConfig->default_connection;
  10. $sConnection = $connection != '' ? $connection : $sDefault;
  11.  
  12. $aSource = $oConfig->$sConnection;
  13.  
  14. $sSource = sprintf('%s:host=%s;dbname=%s',
  15. $aSource['type'],
  16. $aSource['host'],
  17. $aSource['database']
  18. );
  19.  
  20. $this->_Conn = new PDO($sSource, $aSource['user'], $aSource['pass']);
  21.  
  22. }
  23.  
  24. public function setResult($method)
  25. {
  26. $this->_sMethod = $method;
  27. }
  28.  
  29. public function update($table)
  30. {
  31. $iCountParams = count($this->_aAttributes);
  32. $iParam = 0;
  33.  
  34. if($iCountParams)
  35. {
  36. $sQuery = "UPDATE `" . $table . "` SET ";
  37.  
  38. foreach($this->_aAttributes as $sParam => $mValue)
  39. {
  40. $iParam++;
  41. $sQuery .= "" . $sParam . " = '" . $mValue . "'";
  42.  
  43. if($iParam < $iCountParams)
  44. $sQuery .= ", ";
  45. }
  46.  
  47. if($this->_sWhere)
  48. $sQuery .= " WHERE " . $this->_sWhere;
  49.  
  50. $this->_sLast = $sQuery;
  51. }
  52.  
  53. return $this;
  54. }
  55.  
  56. public function assign(array $aNewParams, $bSetValues = TRUE)
  57. {
  58. if(!is_bool($bSetValues))
  59. throw new exception('$bSetValues must be boolean!');
  60.  
  61. if($bSetValues === TRUE)
  62. {
  63. foreach($aNewParams as $sParam => $mValue)
  64. {
  65. $this->_aAttributes[$sParam] = $mValue;
  66. }
  67. }
  68. else
  69. {
  70. foreach($aNewParams as $sParam)
  71. {
  72. $this->_aAttributes[$sParam] = NULL;
  73. }
  74. }
  75.  
  76. return $this;
  77. }
  78.  
  79. public function execute($query = '')
  80. {
  81. $query = $query == '' ? $this->_sLast : $query;
  82.  
  83. $this->_rLast = $this->_Conn->query($query, $this->_sMethod);
  84.  
  85. return $this;
  86. }
  87.  
  88. public function get($table)
  89. {
  90. $this->_sLast = 'SELECT * FROM `'.$table.'`';
  91.  
  92. return $this;
  93. }
  94.  
  95. public function insert($table)
  96. {
  97. $sKeys = implode(' , ', array_keys($this->_aAttributes));
  98. $sValues = implode('" , "', array_values($this->_aAttributes));
  99.  
  100. $this->_sLast = ('insert into '.$table.' ('.$sKeys.') VALUES ("'.$sValues.'")');
  101.  
  102. return $this;
  103. }
  104.  
  105. public function delete($table)
  106. {
  107. $this->_sLast = 'DELETE FROM `'.$table.'`';
  108.  
  109. return $this;
  110. }
  111.  
  112. public function where($what, $where)
  113. {
  114. $this->_sLast .= ' WHERE '.$what.' = "'.$where.'"';
  115.  
  116. return $this;
  117. }
  118.  
  119. public function count($what)
  120. {
  121. $this->_sLast = 'SELECT COUNT(*) as count FROM '.$what;
  122.  
  123. return $this;
  124. }
  125.  
  126. public function query()
  127. {
  128. return $this->_sLast;
  129. }
  130.  
  131. public function limit($ile, $max)
  132. {
  133. $this->_sLast .= ' LIMIT '.$ile.', '.$max;
  134.  
  135. return $this;
  136. }
  137.  
  138. public function order($what, $type = 'asc')
  139. {
  140. $this->_sLast .= ' ORDER BY '.$what.' '.$type;
  141.  
  142. return $this;
  143. }
  144.  
  145. public function fetchAll()
  146. {
  147. foreach ($this->fetch() as $Row)
  148. $Rows [] = $Row;
  149.  
  150. return $Rows;
  151. }
  152.  
  153. public function fetchOne()
  154. {
  155. $aRows = $this->fetchAll();
  156. return $aRows[0];
  157. }
  158.  
  159. public function fetchRow($row)
  160. {
  161. $aRow = $this->fetchOne();
  162.  
  163. return $aRow[$row];
  164. }
  165.  
  166. public function fetch()
  167. {
  168. if (eregi('SELECT COUNT', $this->_sLast)):
  169. $rResult = $this->_rLast;
  170.  
  171. foreach ($rResult as $sRow)
  172. return $sRow['count'];
  173. endif;
  174.  
  175. return $this->_rLast;
  176. }
  177.  
  178. }
  179. ?>


Przykłady wykorzystania mogę napisać na PW osobom które będą zainteresowane, choć myślę, że klasa nie ma zbyt wiele innowacji i każdy średniozaawansowany programista php da sobie radę z wykorzystaniem winksmiley.jpg


--------------------
Nawet, jeżeli nie jesteś zainteresowany usługami IT ani outsourcingiem, a Twoją pasją jest programowanie - zobacz naszą stronę. Piszemy dużo fajnych use-caseów, jak podchodzimy do tematu programowania dla naszych klientów. A tak na co dzień tworzymy budujemy mvp oraz tworzymy platformę b2b.
Go to the top of the page
+Quote Post
Xniver
post 2.03.2008, 22:11:27
Post #5





Grupa: Zarejestrowani
Postów: 108
Pomógł: 26
Dołączył: 29.02.2008

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


A nie lepiej już użyć PDO/Creole/Propel(ORM)?
Go to the top of the page
+Quote Post
matix
post 2.03.2008, 22:47:50
Post #6





Grupa: Zarejestrowani
Postów: 278
Pomógł: 10
Dołączył: 13.02.2007
Skąd: Rybnik

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


@Xniver:

A na czym jest oparta ta klasa? winksmiley.jpg
Creole? Proszę bardzo. Mówisz masz - też mam taką klase winksmiley.jpg

  1. <?
  2. // include Creole
  3. require_once 'creole/Creole.php';
  4.  
  5. class db_creole {
  6. private $_Conn, $_rLast, $_sLast, $_aAttributes, $_sMethod;
  7.  
  8. public function __construct($connection = '')
  9. {
  10. $oConfig = new config('database');
  11.  
  12. $sDefault = $oConfig->default_connection;
  13. $sConnection = $connection != '' ? $connection : $sDefault;
  14.  
  15. $aSource = $oConfig->$sConnection;
  16.  
  17. $sSource = sprintf('%s://%s:%s@%s/%s',
  18. $aSource['type'],
  19. $aSource['user'],
  20. $aSource['pass'],
  21. $aSource['host'],
  22. $aSource['database']
  23. );
  24.  
  25. $this->_Conn = Creole::getConnection($sSource);
  26.  
  27. }
  28.  
  29. public function setResult($method)
  30. {
  31. $this->_sMethod = $method;
  32. }
  33.  
  34. public function update($table)
  35. {
  36. $iCountParams = count($this->_aAttributes);
  37. $iParam = 0;
  38.  
  39. if($iCountParams)
  40. {
  41. $sQuery = "UPDATE `" . $table . "` SET ";
  42.  
  43. foreach($this->_aAttributes as $sParam => $mValue)
  44. {
  45. $iParam++;
  46. $sQuery .= "" . $sParam . " = '" . $mValue . "'";
  47.  
  48. if($iParam < $iCountParams)
  49. $sQuery .= ", ";
  50. }
  51.  
  52. if($this->_sWhere)
  53. $sQuery .= " WHERE " . $this->_sWhere;
  54.  
  55. $this->_sLast = $sQuery;
  56. }
  57.  
  58. return $this;
  59. }
  60.  
  61. public function assign(array $aNewParams, $bSetValues = TRUE)
  62. {
  63. if(!is_bool($bSetValues))
  64. throw new exception('$bSetValues must be boolean!');
  65.  
  66. if($bSetValues === TRUE)
  67. {
  68. foreach($aNewParams as $sParam => $mValue)
  69. {
  70. $this->_aAttributes[$sParam] = $mValue;
  71. }
  72. }
  73. else
  74. {
  75. foreach($aNewParams as $sParam)
  76. {
  77. $this->_aAttributes[$sParam] = NULL;
  78. }
  79. }
  80.  
  81. return $this;
  82. }
  83.  
  84. public function execute($query = '')
  85. {
  86. $query = $query == '' ? $this->_sLast : $query;
  87.  
  88. $this->_rLast = $this->_Conn->executeQuery($query, $this->_sMethod);
  89.  
  90. return $this;
  91. }
  92.  
  93. public function get($table)
  94. {
  95. $this->_sLast = 'SELECT * FROM `'.$table.'`';
  96.  
  97. return $this;
  98. }
  99.  
  100. public function insert($table)
  101. {
  102. $sKeys = implode(' , ', array_keys($this->_aAttributes));
  103. $sValues = implode('" , "', array_values($this->_aAttributes));
  104.  
  105. $this->_sLast = ('insert into '.$table.' ('.$sKeys.') VALUES ("'.$sValues.'")');
  106.  
  107. return $this;
  108. }
  109.  
  110. public function delete($table)
  111. {
  112. $this->_sLast = 'DELETE FROM `'.$table.'`';
  113.  
  114. return $this;
  115. }
  116.  
  117. public function where($what, $where)
  118. {
  119. $this->_sLast .= ' WHERE '.$what.' = "'.$where.'"';
  120.  
  121. return $this;
  122. }
  123.  
  124. public function count($what)
  125. {
  126. $this->_sLast = 'SELECT COUNT(*) as count FROM '.$what;
  127.  
  128. return $this;
  129. }
  130.  
  131. public function query()
  132. {
  133. return $this->_sLast;
  134. }
  135.  
  136. public function limit($ile, $max)
  137. {
  138. $this->_sLast .= ' LIMIT '.$ile.', '.$max;
  139.  
  140. return $this;
  141. }
  142.  
  143. public function order($what, $type = 'asc')
  144. {
  145. $this->_sLast .= ' ORDER BY '.$what.' '.$type;
  146.  
  147. return $this;
  148. }
  149.  
  150. public function fetchAll()
  151. {
  152. foreach ($this->fetch() as $Row)
  153. $Rows [] = $Row;
  154.  
  155. return $Rows;
  156. }
  157.  
  158. public function fetchOne()
  159. {
  160. $aRows = $this->fetchAll();
  161. return $aRows[0];
  162. }
  163.  
  164. public function fetchRow($row)
  165. {
  166. $aRow = $this->fetchOne();
  167.  
  168. return $aRow[$row];
  169. }
  170.  
  171. public function fetch()
  172. {
  173. if (eregi('SELECT COUNT', $this->_sLast)):
  174. $rResult = $this->_rLast;
  175.  
  176. foreach ($rResult as $sRow)
  177. return $sRow['count'];
  178. endif;
  179.  
  180. return $this->_rLast;
  181. }
  182.  
  183. }
  184. ?>


Pozdro =)


--------------------
Nawet, jeżeli nie jesteś zainteresowany usługami IT ani outsourcingiem, a Twoją pasją jest programowanie - zobacz naszą stronę. Piszemy dużo fajnych use-caseów, jak podchodzimy do tematu programowania dla naszych klientów. A tak na co dzień tworzymy budujemy mvp oraz tworzymy platformę b2b.
Go to the top of the page
+Quote Post
Xniver
post 2.03.2008, 23:04:11
Post #7





Grupa: Zarejestrowani
Postów: 108
Pomógł: 26
Dołączył: 29.02.2008

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


Sorki, nie zauważyłem ,że używasz już PDO(myślałem ,że zwykłe mysql_*). A poza tym polecam używanie Propela, bardzo fajnie się z niego korzysta.
Go to the top of the page
+Quote Post

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: 23.06.2025 - 01:23