0

I have a table which looks something like the following (first row is columns):

|section | col1 | col2 |
|----------------------|
|bananas | val  | val2 |
|----------------------|
|peaches | val  | val2 |

With some code to check if a section value matches up with one of the values in an array:

$sectionscope = Array('bananas', 'apples');

$sections = mysql_query("SELECT section FROM table WHERE col1=val AND col2=val2");

if (mysql_num_rows($sections)) {

    $i = 0;

    while ($row = mysql_fetch_array($sections)) {

        if (in_array($row[$i], $sectionscope)) {

            $section = $sectionscope[array_search($row[$i], $sectionscope)];

            $section_is_valid = 1;

        }

        $i++;

    }

}

If I echo the output from the while loop using echo $row[$i], it gives me: bananas

Doing the select from PHPmyadmin works fine

Can you tell me what I'm doing wrong here? Thanks,

SystemError

1
  • Why don't you query for the sections you want in the first place? Commented Nov 20, 2011 at 5:29

1 Answer 1

2

Why are you incrementing $i in the while loop. Your query will return two rows and when you loop through the results, you can access the section value using $row[0] each time.

while ($row = mysql_fetch_array($sections)) {
echo $row[0];    
}

This will print bananas and peaches.

In your code, when you enter the while loop second time, you are trying to retrieve section value using $row[1] (since your $i has incremented to 1), which will be null since your query result only contains one column.

Sign up to request clarification or add additional context in comments.

1 Comment

Woops, classic logical mistake. I keep thinking about the rows as iterating across the index numbers when those are fields not rows. Thanks

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.