1

I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.

$results = array();

foreach($this->columns as $column){

    $current = array();

    while($row = mysql_fetch_array($this->results)){
        $current[] = $row[$column];
        print_r($current);
        echo '<br><br>';
    }

    $results[$column] = $current;

}

print_r($results);

return mysql_fetch_array($this->results);

This works, but the while loop only works on the first column. The print_r($results); shows the following:

Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )

Can anybody shed some light? Thanks in advance!

1
  • Can't see the need for going through the columns manually, the MYSQL_ASSOC flag on mysql_fetch_array will give you an array with only the column names as indices anyway. Commented May 10, 2010 at 0:09

2 Answers 2

4

It's because you already fetched every row, and the internal pointer is at the end. The next while, mysql_fetch_array() will immediately return false. You can reset the pointer to the first row:

mysql_data_seek($this->results, 0);

Put this just before

while($row = mysql_...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks heaps! fixed it completely! Just one question: is there an equivalent when looping through a nested array?
0

I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:

foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.