SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2010
    Location
    Uk
    Posts
    53
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PDO fetch/fetchAll

    Hi there,
    I'm trying to pull data from MySQL, basically when I fetch from the result set a multi-dimensional array is created. And this means I have to use a loop inside another loop to start manipulating the data. I guess I want to have it create a single-dimensional array so I can use a single loop to manipulate data. Below is the code:

    PHP Code:
    class List {

         public function 
    __contruct(){
            
    $this->db = new Database();
         }
         public function 
    getAll(){
            if(
    $sth $this->db->query('SELECT * FROM admin')){
                
    $sth->setFetchMode(PDO::FETCH_ASSOC);
                return 
    $sth->fetchAll();
           }
         }

    ...and calling the method from class..

    PHP Code:
    $list = new List();

    $result $list->getAll();

    while(
    $row $result){
      echo 
    $row['first_name'];
      echo 
    $row['last_name'];
      echo 
    $row['email'];

    I'm kind of confused a bit, what I'm I doing wrong? if I print_r on result this is what I am getting:

    PHP Code:
    print_r($result);

    Array
    (
        [
    0] => Array
            (
                [
    id] => 1
                
    [first_name] => David
                
    [last_name] => Daniels
                
    [email] => dave@yahoo.com
            
    )

        [
    1] => Array
            (
                [
    id] => 2
                
    [first_name] => stacey
                
    [last_name] => stone
                
    [email] => stace@gmail.com
            
    )



  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,501
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    Don't use while to loop through an array, use foreach: http://www.php.net/foreach

  3. #3
    SitePoint Enthusiast
    Join Date
    Mar 2010
    Location
    Uk
    Posts
    53
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah works...

    PHP Code:
    foreach ($result as $value){

      echo 
    $value['first_name'] . ' ' .$value['last_name'] . ' ' .$value['email'];

    I feel stupid now.. this is so easy. I guess i was freaked out by print_r showing multi-dimensional array. Thank you very much


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •