SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using foreach to print SQL results array?

    hi,
    Is this possible? Or am I missing something?

    Here is my code..

    Code:
    $query2 = "SELECT * FROM employer";
    $result2 = mysql_query($query2);
    
    echo mysql_num_rows($result2);
    
    foreach ($result2 as $key=>$value) { 
    echo $value;
    
    }
    This is not printing anything?

    thanks for your time..

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,510
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    A mysql result set is not an array. You can't use foreach. Use while instead, and get one row at a time from the result set with mysql_fetch_array:
    http://www.php.net/manual/en/functio...etch-array.php

  3. #3
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    If you were using the PDO library rather than MySQL, you could do it.

    With MySQL you use MySQL_Fetch_Assoc/Array:
    PHP Code:
    $employerQuery 'SELECT * FROM employer';
    $employerResult MySQL_Query($query2);
    while(
    $row MySQL_Fetch_Assoc($employerResult)){ 
        
    //$row is now an array, containing the fields for that row:
        
    echo $row['Name']; //gets the Name of this row

    That will repeat for every result found.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  4. #4
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    cool, thanks for the advice guys!!


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
  •