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

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....

share|improve this question
Based on your update, the reason is: Rows do not exist where vol in ('2','3','4') – Fosco Jun 3 '11 at 18:51
try echoing the $page inside the while loop. – Paulraj Jun 3 '11 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. – Martin Vrkljan Jun 3 '11 at 18:55

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
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 – thomas Jun 3 '11 at 19:01
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 Jun 3 '11 at 19:09
@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. – Fosco Jun 3 '11 at 19:09

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.