Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is the best way to accomplish this?

I have a PHP function that outputs a MySQL while loop. It works fine, displays every row as expected. However, I need to not echo the results, but rather put them as a variable to work with preexisting code. Changing that obviously limits it to only one result currently.

I assume it's got to be inserted as an array of sorts. Thinking about looping a loop is making my head hurt haha.

Any help would be much appreciated.

share|improve this question
5  
The error is on line 15 – Greg Nov 8 '12 at 18:35
how did you know that ? – Ionut Flavius Pogacian Nov 8 '12 at 18:39

closed as not a real question by vascowhite, tereško, bažmegakapa, Starx, Andy Hayden Nov 9 '12 at 0:12

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

Just do this,

 $result_rows = array();
 while ($row = mysql_fetch_assoc($result)) {
  $result_rows[] = $row; //or $row['fieldname'] if you're looking for something specific
 } 

Note: MYSQL extensions are deprecated, use MySQLi or PDO_MySQL if possible.

share|improve this answer
2  
And please use mysqli_fetch_assoc() :) – Alvar FinSoft Soome Nov 8 '12 at 18:37
1  
And also initialize the array before trying to append to it. – Clarence Nov 8 '12 at 18:38

You could use something like this

$resultsArray = Array();

$statement = $db->query("SELECT * FROM table");

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {

    $resultsArray [] = array(
        'field1' => $row["column1"],
        'field2' => $row["column2"],
        'field3' => $row["column3"]);
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.