SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Understanding MAX in SQL with PHP

    Hello!
    I'm trying to pull off the largest index for a particular group (the $user_id's each have several $course_id's associated with them). I'm using the following PHP/SQL to get the info from my database:

    PHP Code:
    function getlastCourseTaught($read,$user_id) {
        
    $sql "SELECT MAX(course_id)
                FROM courses
                WHERE user_id = 
    $user_id";
        return 
    $read->fetchAll($sql);

    The code works but I'm having problems getting at the actual ID. When I print_r my results, I get:

    Array ( [0] => Array ( [MAX(course_id)] => 1 ) )

    So, two questions:
    1) Why is SQL giving me back an array? Doesn't the MAX just return one specific number?
    2) How can I untangle the "array within the array" to get at the MAX(course_id) of "1".

    Thanks!
    -Eric

    PS IF this thread is more of a PHP question, please move it by all means.

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,411
    Mentioned
    149 Post(s)
    Tagged
    4 Thread(s)
    MySQL returns a result set: a number of rows, and each row contains a number of columns.
    The fetchAll function you're calling is apparently transforming the MySQL result set in a multidimensional array: an array that contains the rows, and each row-element is an array that contains the columns.

    In this case, the result is an array of 1 row, that contains an array of 1 column.

    To get the number, first of all I'd use an alias in the query:
    Code:
    SELECT MAX(course_id) AS maxid
    That way it's easier to address it in your code:
    Code PHP:
    $result = getlastCourseTaught($read,$user_id);
    echo $result[0]['maxid'];

  3. #3
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks so much...your response makes perfect sense....


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
  •