1

Name pretty much explains it all--

I have an array and I want to run a query for each item in the array

Two variables come from this, volume and page number -- the volumes are contained within the array and I need to pull the respective page numbers for each volume

heres my code:

$volsArr = array(1, 2, 3, 4);

foreach ($volsArr as $volume) {
 $pages = mysql_query("SELECT page FROM $table WHERE vol = '$volume' LIMIT 1");
    if (!$pages) { die("Query to show fields from table failed"); }
      while($row = mysql_fetch_array($pages)) {
       $page = $row['page'];
      }
    echo 'volume is '.$volume.'';
    echo 'page is '.$page.'';
   }

I can't figure out what the issue I'm having is, I am getting an output like this:

Volume is 1 Page is 40

(this is correct for volume 1)

Volume is 2 Page is 40

(page should be 8)

Volume is 3 Page is 40

(page should be different again)

etc...

I tried unset($page) before closing the loop but that doesn't seem to do anything, any help, please!

And I also tried moving the echos so they are inside the while($row...) loop, but that will only provide me with output for the first item in the array....

3
  • Based on your update, the reason is: Rows do not exist where vol in ('2','3','4') Commented Jun 3, 2011 at 18:51
  • try echoing the $page inside the while loop. Commented Jun 3, 2011 at 18:53
  • Also, due to the "LIMIT 1" in the query, you don't really need the while loop; just use mysql_fetch_assoc ($result) once to get that single row. You can then use mysql_num_rows ($result) to check if the query returned anything. EDIT: Sorry, use mysql_num_rows before fetching. Commented Jun 3, 2011 at 18:55

1 Answer 1

1

Based on your update, the reason is: Rows do not exist where vol in ('2','3','4')

$page is never being updated because there are no rows to fetch.

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

3 Comments

it seems like this is the issue but its blowing my mind because there is data in the row when i view it via myadmin... EDIT: also the query returns the proper info in myadmin
turns out I set my array up improperly and it had nothing to do with the query -- thanks for pointing this out though because I don't think I would have ever figured it out on my own -- it's always right in front of my face...
@thomas Try building the query in a string first and echoing that so you can test exactly what the php script is going to execute.

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.