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

I have a table called people with the columns id (PK), fname, and lname.

It's simple enough to setup a loop out of the data:

$rs = mysql_query("SELECT * FROM people");
while($row=mysql_fetch_array($rs)){
    ...do stuff...
}

However, what I'm looking to do is loop the column/value pairs into an array automatically.

So, if I added a new column for email I can call the central function and just pull from $results['email'] while looping through the array.

share|improve this question
 
What happens if you try to do that with your current code? Do you get an error? What is the error message? –  Mark Byers Jul 5 '12 at 18:53
add comment

2 Answers

up vote 2 down vote accepted

Use mysql_fetch_assoc(), it returns an associated array with column names as values.

share|improve this answer
 
This works but only returns the first result. How would I get all of the results? –  Fluidbyte Jul 5 '12 at 18:54
 
See this answer –  MrSlayer Jul 5 '12 at 18:55
add comment
$rs = mysql_query("SELECT * FROM people");
$results = array();
while(false !== ($row=mysql_fetch_assoc($rs))){
    $id = $row['id'];
    $results[$id] = $row;
}

$results is now a multi-dimensional array, each element being an array of fieldname => fieldvalue elements

Array
(
    [1] => Array
        (
            [id] => 1
            [fname] => John
            [lname] => Smith
        )
    [3] => Array
        (
            [id] => 3
            [fname] => Karen
            [lname] => Berry
        )
)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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