Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2010
    Posts
    20

    Unanswered: Get query results using array

    Hi everybody,

    just would like to ask to someone more expert than me if it's possible to use a variable (or maybe better, array) as name of the column from which I should get the results with the query.

    So I mean instead of this:

    while ($results = mysql_fetch_array($query)) {
    $id = $results['id'];
    $name = $results['name'];
    ...
    }

    ... something like this

    $fields = array("id","name", ...);
    $i = 0;

    while ($results = mysql_fetch_array($query)) {
    $id = $results[$fields[$i]];
    $name = $results[$fields[$i]];
    ...
    $i++
    }

    Ok, this doesn't work... but is there maybe some other way...?

    Thanks

  2. #2
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    Actually this does work but not implemented correctly.

    Code:
    $fields = array("id","name", ...);
    
    while ($results = mysql_fetch_array($query)) {
      $i = 0;
      $id = $results[$fields[$i++]];
      $name = $results[$fields[$i++]];
      ...
    }
    Your looping of the array containing the field names was not correct. You should initially assign $i = 0 inside the loop and after accessing the first entry we auto increment this value by 1 ($i++).

    Alternatively you code use the following

    Code:
    while ($results = mysql_fetch_assoc($query)) {
      extract($results);
      // $id, $name is created based on the structure of the array being returned when using extract
      ...
    }
    Last edited by it-iss.com; 07-17-12 at 13:55.
    Ronan Cashell
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

Posting Permissions

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