How do you save rows to an array and print out in PHP using ODBC?

15,046

Declare an array before and assign the values to it:

$rows = array();

while($myRow = odbc_fetch_array( $result )){ <--lots of rows
    $rows[] = $myRow;
}

Then you can print it e.g. this way:

foreach($rows as $row) {
   foreach($row as $key => $value) {
       echo $key . ': '. $value;
   }
}

or however you want to.

You don't have to access and assign $thisResult['name'] = $myRow["name"] in your while loop as $myRow already is an array. You just copy the values which is unnecessary.


You say you have a lot of rows. Depending of what you really want to do with data, it might be better to put all this functionality into the while loop to avoid creating an array.

Share:
15,046
johnny
Author by

johnny

Updated on June 04, 2022

Comments

  • johnny
    johnny about 2 years

    I have the following:

    while($myRow = odbc_fetch_array( $result )){ <--lots of rows
        $thisResult['name'] = $myRow["name"] ;
        $thisResult['race'] = $myRow["race"] ;
        $thisResult['sex'] = $myRow["sex"];
        $thisResult['dob'] = $myRow["dob"];
    }
    

    I can't figure out how to print this back out.

    I want to get each row and iterate through each row in the array like a datareader. I'm not sure what to do. I do not want to do the echo in the while. I need to be able to print it out elsewhere. But I don't think I've done it right here to be able to print it later.

    I also tried, this, however:

    while($myRow = odbc_fetch_array( $result )){ <--lots of rows
         print($thisResult[$myRow["name"]] = $myRow);
    }
    

    I then tried:

    while($myRow = odbc_fetch_array( $result )){ <--lots of rows
        print (odbc_result($myRow,"name"));
    }
    

    but got an error.

    Thank you for any help.

    EDIT: when I do this:

    while($myRow = odbc_fetch_array( $result )){
        print ($myRow["name"]);
    }
    

    I get undefined index name. I am mainly concerned with saving to an array but I have to be able to do it in the loop first.

  • webbiedave
    webbiedave about 14 years
    I think you mean $rows[] = $myRow;