Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [php] klasa dodawająca użytkowników + wysyłanie maila, pobranie ID
Lejto
post
Post #1





Grupa: Zarejestrowani
Postów: 1 385
Pomógł: 48
Dołączył: 23.05.2007

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


Mam problem z klasą

Tak wykonuje rejestracje:
  1. $u->username = htmlspecialchars($_POST['username']);
  2. $u->password = htmlspecialchars($_POST['password1']);
  3. $u->emailAddr = htmlspecialchars($_POST['mail']);
  4. $u->imie = htmlspecialchars($_POST['imie']);
  5. $u->nazwisko = htmlspecialchars($_POST['nazwisko']);
  6. $token = $u->setInactive();
  7. echo '<p><strong>Dziękujemy za ' .
  8. 'zarejestrowanie się.</strong></p><p>Należy pamiętać o zweryfikowaniu konta i kliknąć w łącze załączone w mailu który sotał wysłany';


Dodaje pomyślnie dane do bazy.
Gorzej jest z pobraniem id zarejestrowanego użytkownika. (jak wysyłam maila to potrzebuje te dane)
pobieram tak:
  1. $user->userId;

nic nie zwraca

Klasa:
  1. <?
  2. class User extends functions
  3. {
  4. public $uid;
  5. public $fields = array();
  6. protected $sql;
  7. public $userId;
  8.  
  9. public function __construct($sql)
  10. {
  11. $this->sql = $sql;
  12. $this->uid = null;
  13. $this->fields = array('username' => '',
  14. 'password' => '',
  15. 'emailAddr' => '',
  16. 'gg' => '',
  17. 'imie' => '',
  18. 'nazwisko' => '',
  19. 'isActive' => false);
  20. }
  21. public function __get($field)
  22. {
  23. if($field == 'userId')
  24. {
  25. return $this->uid;
  26. }
  27. else
  28. {
  29. return $this->fields[$field];
  30. }
  31. }
  32. public function __set($field, $value)
  33. {
  34. if(array_key_exists($field, $this->fields))
  35. {
  36. $this->fields[$field] = $value;
  37. }
  38. }
  39. public function validateUserName($username)
  40. {
  41. if(strlen($username)<3)
  42. {
  43. echo 'Nazwa użytkownika musi zawierać co najmniej 3 znaki.';
  44. }
  45. else
  46. {
  47. return true;
  48. }
  49. if(strlen($username)>20)
  50. {
  51. echo 'Za długa nazwa użytkownika max 20 znaków.';
  52. }
  53. else
  54. {
  55. return true;
  56. }
  57. }
  58. public function validateEmailAddr($email)
  59. {
  60. return filter_var($email, FILTER_VALIDATE_EMAIL);
  61. if(false)
  62. {
  63. echo 'Niepoprawny adres e-mail';
  64. }
  65. }
  66. public function getById($uid)
  67. {
  68. $db = $this->sql;
  69.  
  70. $u = new User($db);
  71. $sql = $db->query('select * from users where user_id = "'.$uid.'"');
  72.  
  73. if($sql->num_rows)
  74. {
  75. $row = $sql->fetch_array();
  76. $u->username = $row['username'];
  77. $u->password = $row['password'];
  78. $u->emailAddr = $row['email_addr'];
  79. $u->isActive = $row['is_active'];
  80. $u->imie = $row['imie'];
  81. $u->nazwisko = $row['nazwisko'];
  82. $u->uid = $uid;
  83. }
  84. return $u;
  85. }
  86.  
  87. public function getByUsername($username)
  88. {
  89. $db = $this->sql;
  90. $u = new User($db);
  91. $sql = $db->query('select * from users where username = "'.$username.'" and is_active = 1');
  92.  
  93. if($sql->num_rows)
  94. {
  95. $row = $sql->fetch_array();
  96. $u->password = $row['password'];
  97. $u->username = $row['username'];
  98. $u->emailAddr = $row['email_addr'];
  99. $u->isActive = $row['is_active'];
  100. $u->imie = $row['imie'];
  101. $u->nazwisko = $row['nazwisko'];
  102. $u->uid = $row['user_id'];
  103. }
  104. return $u;
  105. }
  106.  
  107. public function save()
  108. {
  109.  
  110.  
  111. $db = $this->sql;
  112. $data = date('d.m.y H:i:s');
  113.  
  114. if($this->uid)
  115. {
  116. $sql = $db->query('update USERS set username = "'.$this->username.'", password = "'.$this->password.'",
  117. email_addr = "'.$this->emailAddr.'", is_active = "'.$this->isActive.'" where user_id = "'.$this->userId.'"');
  118.  
  119.  
  120. }
  121. else
  122. {
  123. $sql = $db->query('insert into users (username, password, email_addr, is_active, gg,imie,nazwisko,data)
  124. values ("'.$this->username.'", "'.sha1($this->password).'", "'.$this->emailAddr.'", "0",
  125. "'.htmlspecialchars($_POST['gg']).'","'.$this->imie.'","'.$this->nazwisko.'","'.$data.'")');
  126. if(!$sql)
  127. {
  128. var_dump($this->password);
  129. }
  130. }
  131. }
  132.  
  133. public function setInactive()
  134. {
  135. $db = $this->sql;
  136. $this->isActive = false;
  137. $this->save();
  138.  
  139. $token = $this->random_text(5);
  140. $sql = $db->query('insert into users_pending (user_id, token) values ("'.$this->uid.'", "'.$token.'")');
  141.  
  142. return $token;
  143. }
  144.  
  145. public function setActive($token)
  146. {
  147. $db = $this->sql;
  148.  
  149. $sql = $db->query('select token from users_pending where user_id = "'.$this->uid.'" and token = "'.$token.'"');
  150.  
  151. if(!$sql->num_rows)
  152. {
  153. return false;
  154. }
  155. else
  156. {
  157. $sql = $db->query('delete from users_pending where user_id = "'.$this->uid.'" and token = "'.$this->token.'"');
  158. $this->isAdcive = true;
  159. $this->save();
  160. return true;
  161. }
  162. }
  163. }


--------------------
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi (1 - 9)
wiiir
post
Post #2





Grupa: Zarejestrowani
Postów: 260
Pomógł: 34
Dołączył: 22.02.2010

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


a co ma ci to zwrocic??

moze nie umiem programowac obiektowo jak ty ale nie widze funkcji userId ktora by cos miala zwracac.. zreszta ja bym napisal $user->userId(); pod warunkiem ze funkcja istnieje w extends functions bo tutaj jej nie widze
Go to the top of the page
+Quote Post
Ormin
post
Post #3





Grupa: Zarejestrowani
Postów: 64
Pomógł: 0
Dołączył: 3.02.2009

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


a spróbuj po prostu $user->uid ?
Go to the top of the page
+Quote Post
Lejto
post
Post #4





Grupa: Zarejestrowani
Postów: 1 385
Pomógł: 48
Dołączył: 23.05.2007

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


też robiłem i nic, zwrócić ma ID użytkownika który się zarejestrował


--------------------
Go to the top of the page
+Quote Post
wiiir
post
Post #5





Grupa: Zarejestrowani
Postów: 260
Pomógł: 34
Dołączył: 22.02.2010

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


kurde nie zauwazylem tego ;

  1. public $userId;


nic nie zwraca, a wlasciwie zwraca ci zmienna userId, dlatego ze jak mi sie wydaje wylowanie u->userId; szuka najpierw zmiennej o polu jakie wywolujesz a jak nie znajdzie dopiero pozniej wchodzi do __get i wykonuje warunek.. sprobuj tak

  1. IF($field == 'showUserId')
  2. {
  3. RETURN $this->uid;
  4. }
  5.  
  6. i wywolaj
  7. $user->showUserId;


Ten post edytował wiiir 27.02.2010, 22:02:14
Go to the top of the page
+Quote Post
Lejto
post
Post #6





Grupa: Zarejestrowani
Postów: 1 385
Pomógł: 48
Dołączył: 23.05.2007

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


niestety nie działa, mam tak:
  1. <?
  2. class User
  3. {
  4. public $uid;
  5. public $fields = array();
  6. protected $sql;
  7.  
  8. public function __construct($sql)
  9. {
  10. $this->sql = $sql;
  11. $this->uid = null;
  12. $this->fields = array('username' => '',
  13. 'password' => '',
  14. 'emailAddr' => '',
  15. 'gg' => '',
  16. 'isActive' => false);
  17. }
  18. public function __get($field)
  19. {
  20. if($field == 'userId')
  21. {
  22. return $this->uid;
  23. }
  24. else
  25. {
  26. return $this->fields[$field];
  27. }
  28. if($field == 'showUserId')
  29. {
  30. return $this->uid;
  31. }
  32. }
  33. public function __set($field, $value)
  34. {
  35. if(array_key_exists($field, $this->fields))
  36. {
  37. $this->fields[$field] = $value;
  38. }
  39. }
  40. public function validateUserName($username)
  41. {
  42. if(strlen($username)<3)
  43. {
  44. echo '<span style="color:#F00;">Nazwa użytkownika musi zawierać co najmniej 3 znaki.</span>';
  45. }
  46. else
  47. {
  48. return true;
  49. }
  50. if(strlen($username)>20)
  51. {
  52. echo 'Za długa nazwa użytkownika max 20 znaków.';
  53. }
  54. else
  55. {
  56. return true;
  57. }
  58. }
  59. public static function validateEmailAddr($email)
  60. {
  61. return filter_var($email, FILTER_VALIDATE_EMAIL);
  62. if(false)
  63. {
  64. echo 'Niepoprawny adres e-mail';
  65. }
  66. }
  67. public function getById($uid)
  68. {
  69. $db = $this->sql;
  70.  
  71. $u = new User($db);
  72. $sql = $db->query('select * from users where user_id = "'.$uid.'"');
  73.  
  74. if($sql->num_rows)
  75. {
  76. $row = $sql->fetch_array();
  77. $u->username = $row['username'];
  78. $u->password = $row['password'];
  79. $u->emailAddr = $row['email_addr'];
  80. $u->isActive = $row['is_active'];
  81. $u->uid = $uid;
  82. }
  83. return $u;
  84. }
  85.  
  86. public function getByUsername($username)
  87. {
  88. $db = $this->sql;
  89. $u = new User($db);
  90. $sql = $db->query('select * from users where username = "'.$username.'" and is_active = 0');
  91.  
  92. if($sql->num_rows)
  93. {
  94. $row = $sql->fetch_array();
  95. $u->password = $row['password'];
  96. $u->username = $row['username'];
  97. $u->emailAddr = $row['email_addr'];
  98. $u->isActive = $row['is_active'];
  99. $u->uid = $row['user_id'];
  100. }
  101. return $u;
  102. }
  103.  
  104. public function save()
  105. {
  106.  
  107.  
  108. $db = $this->sql;
  109. $data = date('d.m.y H:i:s');
  110.  
  111. if($this->uid)
  112. {
  113. $sql = $db->query('update USERS set username = "'.$this->username.'", password = "'.$this->password.'",
  114. email_addr = "'.$this->emailAddr.'", is_active = "'.$this->isActive.'" where user_id = "'.$this->userId.'"');
  115.  
  116.  
  117. }
  118. else
  119. {
  120. $sql = $db->query('insert into users (username, password, email_addr, is_active, gg,data)
  121. values ("'.$this->username.'", "'.sha1($this->password).'", "'.$this->emailAddr.'", "0",
  122. "'.htmlspecialchars($_POST['gg']).'","'.$data.'")');
  123. if(!$sql)
  124. {
  125. }
  126. }
  127. }
  128. public function random_text($count, $rm_similar = false)
  129. {
  130. $chars = array_flip(array_merge(range(0, 9), range('A', 'Z')));
  131.  
  132. if ($rm_similar)
  133. {
  134. unset($chars[0], $chars[1], $chars[2], $chars[5], $chars[8],
  135. $chars['B'], $chars['I'], $chars['O'], $chars['Q'],
  136. $chars['S'], $chars['U'], $chars['V'], $chars['Z']);
  137. }
  138. for ($i = 0, $text = ''; $i < $count; $i++)
  139. {
  140. $text .= array_rand($chars);
  141. }
  142. return $text;
  143. }
  144. public function setInactive()
  145. {
  146. $db = $this->sql;
  147. $this->isActive = false;
  148. $this->save();
  149.  
  150. $token = $this->random_text(5);
  151. $sql = $db->query('insert into users_pending (user_id, token) values ("'.$user->showUserId.'", "'.$token.'")');
  152.  
  153. return $token;
  154. }
  155.  
  156. public function setActive()
  157. {
  158. $db = $this->sql;
  159.  
  160. $sql = $db->query('select token from users_pending where user_id = "'.$this->uid.'" and token = "'.$token.'"');
  161.  
  162. if(!$sql->num_rows)
  163. {
  164. return false;
  165. }
  166. else
  167. {
  168. $sql = $db->query('delete from users_pending where user_id = "'.$this->uid.'" and token = "'.$this->token.'"');
  169. $this->isAdcive = true;
  170. $this->save();
  171. return true;
  172. }
  173. }
  174. public function dane()
  175. {
  176.  
  177. $email = htmlspecialchars($_POST['email']);
  178. $db = $this->sql;
  179. $u = new User($db);
  180. $user = $u->getById($_SESSION['userId']);
  181. if(isset($_POST['submitted']))
  182. {
  183. // sprawdzenie poprawności hasła
  184. $password1 = (isset($_POST['password1']) && $_POST['password1']) ?
  185. sha1($_POST['password1']) : $user->password;
  186. $password2 = (isset($_POST['password2']) && $_POST['password2']) ?
  187. sha1($_POST['password2']) : $user->password;
  188. $password = ($password1 == $password2) ? $password1 : '';
  189. // uaktualnienie rekordu, jeżeli dane wejściowe są poprawne
  190. if ($u->validateEmailAddr($_POST['email']) && $password)
  191. {
  192. $user->emailAddr = $_POST['email'];
  193. $user->password = $password;
  194. $user->save();
  195. echo '<p><strong>Informacje ' .
  196. 'w bazie danych zostały uaktualnione.</strong></p>';
  197. }
  198. else
  199. {
  200. echo '<p><strong>Podano nieprawidłowe ' .
  201. 'dane.</strong></p>';
  202. }
  203. }
  204. ?>
  205. <form action="userpanel/dane" method="post">
  206. <table>
  207. <tr>
  208. <td><label>Nazwa użytkownika</label></td>
  209. <td><input type="text" name="username" disabled="disabled" readonly="readonly" value="<?php echo $user->username; ?>"/></td>
  210. </tr>
  211. <tr>
  212. <td><label for="email">Adres email</label></td>
  213. <td><input type="text" name="email" id="email" value="<?php echo (isset($_POST['email']))? htmlspecialchars($_POST['email']) : $user->emailAddr; ?>"/></td>
  214. </tr>
  215. <tr>
  216. <td><label for="password">Nowe hasło</label></td>
  217. <td><input type="password" name="password1" id="password1"/></td>
  218. </tr>
  219. <tr>
  220. <td><label for="password2">Powtórzenie hasła</label></td>
  221. <td><input type="password" name="password2" id="password2"/></td>
  222. </tr>
  223. <tr>
  224. <td></td>
  225. <td><input type="submit" value="Zapisz"/></td>
  226. <td><input type="hidden" name="submitted" value="1"/></td>
  227. </tr>
  228. </table>
  229. </form>
  230. <?
  231. }
  232. public function menu()
  233. {
  234. ?>
  235. <div id="tabs">
  236. <ul>
  237. <li><a href="userpanel/dane"><span>Dane</span></a></li>
  238. <li><a href="#"><span>Dod. informacje</span></a></li>
  239. <li><a href="#"><span>Avatar</span></a></li>
  240. <li><a href="#"><span>Zdjęcie osobiste</span></a></li>
  241. </ul>
  242. </div>
  243. <?
  244. }
  245. public function information_user($username)
  246. {
  247.  
  248. }
  249.  
  250. }
  251. ?>


--------------------
Go to the top of the page
+Quote Post
slimy
post
Post #7





Grupa: Zarejestrowani
Postów: 9
Pomógł: 0
Dołączył: 13.09.2009

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


A spróbuj wyswietlic całą zawartosc obiektu
  1. print_r($user)

i zobacz czy są potrzebne dane.

  1. public function getByUsername($username)
  2. {
  3. $db = $this->sql;
  4. $u = new User($db);
  5. $sql = $db->query('select * from users where username = "'.$username.'" and is_active = 0');
  6.  
  7. if($sql->num_rows)
  8. {
  9. $row = $sql->fetch_array();
  10. $u->password = $row['password'];
  11. $u->username = $row['username'];
  12. $u->emailAddr = $row['email_addr'];
  13. $u->isActive = $row['is_active'];
  14. $u->uid = $row['user_id'];
  15. }
  16. return $u;
  17. }


Czemu pracując na obiekcie w jego metodzie tworzysz nowy obiekt tego samego typu? Czy nie lepiej zainicjowac zmienne w bieżącym obiekcie? Mozliwe, ze to powoduje blad. W sensie czy wywloujesz:

  1. $user->getByUsername('user');
  2. print $user->uid;


a funkcja nie inicjalizuje zmiennych w tym obiekcie tylko tworzy nowy. winksmiley.jpg Stosujac Twoj kod powinno byc:

  1. $user = $user->getByUsername('user');
  2. print $user->uid;


ale ja bym zmienil ta funkcje by nie tworzyla nowego obiektu - chyba, ze jest to akurat celowe winksmiley.jpg

Ten post edytował slimy 18.04.2010, 22:53:08
Go to the top of the page
+Quote Post
phpion
post
Post #8





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




W metodzie save() nie masz aktualizacji ID obiektu więc nie dziw się, że nie dzieje się to w sposób magiczny. Dodaj tam po wykonaniu INSERT coś w stylu:
  1. $this->uid = 123; // tutaj wstaw pobranie ostatniego ID
Go to the top of the page
+Quote Post
Lejto
post
Post #9





Grupa: Zarejestrowani
Postów: 1 385
Pomógł: 48
Dołączył: 23.05.2007

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


zrobiłem tak
  1. public function save()
  2. {
  3.  
  4.  
  5. $db = $this->sql;
  6. $data = date('d.m.y H:i:s');
  7.  
  8. if($this->uid)
  9. {
  10. $sql = $db->query('update USERS set username = "'.$this->username.'", password = "'.$this->password.'",
  11. email_addr = "'.$this->emailAddr.'", is_active = "'.$this->isActive.'" where user_id = "'.$this->userId.'"');
  12. $sql2 = $db->query('select user_id from users order by user_id desc');
  13. $r = $sql2->fetch_array();
  14. $this->uid = $r[user_id];
  15.  
  16. }
  17. else
  18. {
  19. $sql = $db->query('insert into users (username, password, email_addr, is_active, gg,data)
  20. values ("'.$this->username.'", "'.sha1($this->password).'", "'.$this->emailAddr.'", "0",
  21. "'.htmlspecialchars($_POST['gg']).'","'.$data.'")');
  22. if(!$sql)
  23. {
  24. }
  25. }
  26. }
  27.  
  28. public function setInactive()
  29. {
  30. $db = $this->sql;
  31. $this->isActive = false;
  32. $this->save();
  33.  
  34. $token = $this->random_text(5);
  35. $sql = $db->query('insert into users_pending (user_id, token) values ("'.$this->uid.'", "'.$token.'")');
  36.  
  37. return $token;
  38. }


niestety nie działa


--------------------
Go to the top of the page
+Quote Post
Crozin
post
Post #10





Grupa: Zarejestrowani
Postów: 6 476
Pomógł: 1306
Dołączył: 6.08.2006
Skąd: Kraków

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


Co robi obiekt klasy User?

1) Reprezentuje jeden konkretny rekord z bazy danych
2) Sprawdza poprawność danych wprowadzonych w formularzu
3) Wyświetla sformatowaną odpowiedź
4) Pobiera inne obiekty klasy User z bazy danych
5) Generuje losowe tokeny
6) Przetwarza formularz
7) Wyświetla formularz

A zgodnie z ideą programowania obiektowego: jeden obiekt - jedno zadanie.

Poza tym:
1) W User::__get() masz tzw. dead-code - czyli fragment kodu, który się nigdy nie wykona (chodzi o ten drugi IF z showUserId)
2) Brak jakiegokolwiek powiadamiania czy coś co zostało wykonane (nie) wykonało się poprawnie
3) Wielokrotnie powtarzasz dokładnie ten sam kod różniący się przykładowo jednym waruniem. Google: DRY reguła, Google: KISS reguła
4) htmlspecialchars używa się przed wyświetleniem danych w dokumentach XML/HTML i im podobnych

Tak więc:
1) Poczytaj co nieco teorii na temat programowania obiektowego - bo brniesz w coś czego nie da się sklasyfikować jako OOP - co więcej... to jedynie utrudnia Ci życie
2) Podziel sobie różne zadania na różne obiekty
3) Zaplanuj jak owe obiekty będą ze sobą współpracować
4) Dopiero wtedy bierz się za pisanie
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 Aktualny czas: 19.08.2025 - 13:38