SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Apr 2003
    Location
    canada
    Posts
    126
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    $query->fetch(PDO::FETCH_ASSOC into array

    Hello,

    Im having a hard time loading a table into a array. I need cat_id & category into $categoryArray[] to later use to display on the page.
    any help you can give would be greatly appreciated

    my table(tbl_category)
    Cat_id Category
    1 Accounting
    2 marketing
    3 Finance
    .. ...

    try
    { $query = $db->prepare('SELECT tbl_category.category, tbl_category.cat_id FROM tbl_category ORDER BY tbl_category.category');
    $query->execute();
    while($row=$query->fetch(PDO::FETCH_ASSOC))
    { $categoryArray[] = $row['category']; }

    //foreach($categoryArray as $key1 => $value1)
    //{ foreach($value1 as $key2 => $value2)
    {echo $value1. " ". $key2.'<br />';}
    //}
    }
    catch(PDOException $e)
    { echo 'ERROR: ' . $e->getMessage(); }

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    $query->fetchAll()

    Then consider this:
    PHP Code:
    // spoofing your result set from db
    $rows[] = array('id'=>23'name'=>'Accounts');
    $rows[] = array('id'=>25'name'=>'Sales');

    // set up a blank array first
    $return = array();

    // iterate through results and set them to the new array
    foreach($rows as $key=>$value)
        
    $return[$key] = $value['name']; 

    // take a butchers ...
    var_dump($return); 
    You also want to make your SELECT a bit clearer, no need for the table names if you are not doing JOINS.

    If you are writing the SELECT by hand, you hardly need to prepare it though, is there more you are not showing us?


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
  •