Jump to content
php.lv forumi

nebeidzams loops ar PDO fetch()


jaanisk

Recommended Posts

    public function fetch_row($sql) {
        $result = $this->dbh->query($sql);
        return $result->fetch(PDO::FETCH_ASSOC);
    }

 

    

    $dbh = new DB;
        $query = "SELECT * FROM `hg_users`";
        while($row = $dbh->fetch_row($query)) {
            echo $row['id'];
            echo $row['username'];
        }

 

vēlamais iznākums: peeteris1anna2

iznākums ar manu kodu: peeteris1peeteris1peeteris1peeteris1peeteris1peeteris1peeteris1(...)tikko sāku ņemties ar OOP un PDO, ar ko šādu nebiju saskāries.

kur ir vaina?

Edited by jaanisk
Link to comment
Share on other sites

es jau tikai mācos :)

 

sapratu, ka fetch() tiek lietots citādāk, funkciju tāpēc pārrakstīju šādi:

public function fetch_row($query) {
        $sth = $this->dbh->prepare($query);
        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        return $result;
    }

pieļauju, ka šis jau ir vairāk uz pareizā ceļa, taču nekādīgi nevaru panākt vēlamo rezultātu.

ko es daru tik ļoti nepareizi?

Edited by jaanisk
Link to comment
Share on other sites

solved, tā izskatās

public function fetch_row($query) {
   $sth = $this->dbh->prepare($query);
   $sth->execute();
   $array = $sth->fetchAll(PDO::FETCH_ASSOC);
   return $array;
}

 

$dbh = new DB;
$query = "SELECT * FROM hg_users";
$array = $dbh->fetch_row($query);
foreach($array as $row) {
    echo $row['id'];
    echo $row['username'];
}

Edited by jaanisk
Link to comment
Share on other sites

Saprati, kas bija nepareizi pirmajā kodā?

 

Un funkcijas nosaukums fetch_row tomēr liek domāt, ka funkcija atgriež VIENU rindu, nevis masīvu ar rindām...

 

ja godīgi, tā arī nesapratu, vienkārši dokumentācijā uzgāju, ka ir citādāk.

 

pieļauju, ka tur nekādu fetch nevajag, bet gan return $result un tad izmantot foreach, lai izvilktu datus? ja nē, ar interesi uzklausīšu, kas tur bija nepareizi :)

Edited by jaanisk
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...