0

I'm creating a class book list - there's a master list of books, and a list of the books that the class can be assigned. I need to create an array of the master list, remove the books that have already been assigned to the class, then create a select list of the remaining books. I have most of it working, but I'm stuck on a small part. First, I load the array (the book_id is the key, the book_title is the value):

while ($master_book = mysql_fetch_array($big_book_list)) {
$b_id = $master_book['master_book_list_id'];
$book_list[$b_id] = $master_book['book_title'];
}

then I remove the class's primary book (it's already been set):

unset($book_list[$primary_book]);

now I load an array of the secondary books that have already been assigned (primary and secondary books come from the same list):

$secondary_query = "select * from class_books cb, master_book_list mbl where class_id ='$class_id' and cb.book_id = mbl.master_book_list_id;";
$secondary_list = mysql_query($secondary_query);

Now I remove the books from $secondary_list from the main list:

while ($secondary_book = mysql_fetch_array($secondary_list)) {
  $b_id = $secondary_book['book_id'];
  unset($book_list[$b_id]);
}

at this point, print_r shows my array correctly. but this code:

foreach ($book_list as $book2) {
  $the_key = key($book_list);
  echo $the_key . ' and book2 is '. $book2 . '<br/>';
}

it will iterate the predicted number of times, but the key stays at the same value (which is '2', the first value in the array.

Can anyone see what I'm doing wrong?

ini
  • 201
  • 1
  • 4
  • 14
  • **warning** your code may be susceptible to sql injection attacks. – Daniel A. White Aug 06 '12 at 18:18
  • Don't you mean to use $book2 instead of booklist in that loop? – Daniel MesSer Aug 06 '12 at 18:23
  • You should stop using `mysql_*` functions. They're being deprecated. Instead use [PDO](http://php.net/manual/en/book.pdo.php) (supported as of PHP 5.1) or [mysqli](http://php.net/manual/en/book.mysqli.php) (supported as of PHP 4.1). If you're not sure which one to use, [read this SO article](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons). – Matt Aug 06 '12 at 18:23
  • Oh, in which ways? The only piece of data sent to this procedure gets wrapped in mysql_real_escape_string()... is there something else I should be doing? – ini Aug 06 '12 at 18:24

1 Answers1

3

You can grab the key from the foreach loop:

foreach ($book_list as $the_key => $book2) {
    echo $the_key . ' and book2 is '. $book2 . '<br/>';
}
nickb
  • 59,313
  • 13
  • 108
  • 143
  • Well that was easy :) Exactly what I needed, I can mark this as 'the answer' in 10 minutes. Thank you! – ini Aug 06 '12 at 18:22
  • @ini This *is* spelled out in the php documentation for `foreach` loops. (http://php.net/manual/en/control-structures.foreach.php) – Matt Aug 06 '12 at 18:24