Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Iterator - dlaczego to działa?
spokoloko123
post
Post #1





Grupa: Zarejestrowani
Postów: 114
Pomógł: 12
Dołączył: 15.02.2012

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


  1. <?
  2. class QueryIterator implements Iterator
  3. {
  4. private $result;
  5. private $connection;
  6. private $data;
  7. private $key=0;
  8. private $valid;
  9.  
  10. function __construct($host, $user, $password, $dbname)
  11. {
  12. $this->connection = mysql_connect($host, $user, $password);
  13. mysql_select_db($dbname);
  14. }
  15. //wykonujemy zapytanie o imiona i email
  16. public function exceute($query)
  17. {
  18. $this->result = mysql_query($query);
  19. if (mysql_num_rows($this->result)>0)
  20. $this->next();
  21. }
  22. public function rewind() {}
  23. public function current()
  24. {
  25. return $this->data;
  26. }
  27. public function key()
  28. {
  29. return $this->key;
  30. }
  31. //dane zapisywane są w $data, $valid=true, $key++
  32. public function next()
  33. {
  34. if ($this->data = mysql_fetch_assoc($this->result))
  35. {
  36. $this->valid = true;
  37. $this->key+=1;
  38. }
  39. else
  40. $this->valid = false;
  41. }
  42. public function valid()
  43. {
  44. return $this->valid;
  45. }
  46. }
  47.  
  48. $qi = new QueryIterator("localhost", "user", "pass", "test");
  49. $qi->exceute("SELECT name, email FROM users");
  50. while($qi->valid())
  51. {
  52. print_r($qi->current());
  53. $qi->next();
  54. }
  55. ?>


Nie wiem za bardzo dlaczego to działa ;P. Funkcja key nie jest nigdzie używana a po jej usunięciu wywala błąd.
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
tehaha
post
Post #2





Grupa: Zarejestrowani
Postów: 1 748
Pomógł: 388
Dołączył: 21.08.2009
Skąd: Gdynia

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


Każda tablica ma wewnętrzny wskaźnik, funkcja mysql_fetch_assoc() pobiera tablicę i przesuwa wskaźnik, dlatego przy następnym wywołaniu pobierze kolejny element, funkcja zwróci FALSE kiedy nie będzie już więcej wyników do zwrócenia
Cytat
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead
-> http://www.php.net/mysql_fetch_assoc

Ten post edytował tehaha 10.05.2012, 11:29:36
Go to the top of the page
+Quote Post

Posty w temacie


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

 



RSS Aktualny czas: 15.10.2025 - 05:04