Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [php][mysql] Klasa do obsługi baz danych.
Forum PHP.pl > Forum > PHP
Maciekbjw
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
phpion
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ą...
Maciekbjw
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!
matix
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
Xniver
A nie lepiej już użyć PDO/Creole/Propel(ORM)?
matix
@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 =)
Xniver
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.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.