title: MYSQL PHP Use results of query to requery in foreach loop (complicated - I think)
body: <p>Here's what I want to do: I am making a listmaking application and I have 2 MYSQL databases, one with a table that contains information on each list like name and then a second db that contains lists as individual tables, listitems are rows in those tables.  I want to get select all lists from the first (lookup) table and echo some info and then get all of the corresponding listitems from the corresponding table.  I would like to echo a div with the title from the first table then use that table to also make the second query for the items.  Is it possible to do a foreach loop for each row returned?</p>
  
  <p>Here's my code so far:</p>
  
  <pre><code>$mysqli2 = new mysqli("localhost", "****", "****", "full_lists");
  if ($mysqli2-&gt;connect_errno) {
  echo "Failed to connect to MySQL: (" . $mysqli-&gt;connect_errno . ") " .$mysqli-&gt;connect_error;
  }
  
  $mysqli = new mysqli("localhost", "****", "****", "lists");
  if ($mysqli-&gt;connect_errno) {
  echo "Failed to connect to MySQL: (" . $mysqli-&gt;connect_errno . ") " . $mysqli-&gt;connect_error;
  }
  
  if (!($stmt = $mysqli-&gt;prepare("SELECT listname, dbname FROM lists"))) {
  echo "Prepare failed: (" . $mysqli-&gt;errno . ") " . $mysqli-&gt;error;
  }
  
  if (!$stmt-&gt;execute()) {
  echo "Execute failed: (" . $stmt-&gt;errno . ") " . $stmt-&gt;error;
  }   
  
  $stmt-&gt;bind_result($list, $dbname);
  
  //First statement gets the name of another table in a different database
  
  while ($stmt-&gt;fetch()) {
  $stmt2 = $mysqli2-&gt;prepare("SELECT listitems FROM {$dbname}");
  //Second statement uses first to run another select statement getting
  //table rows
      $stmt2-&gt;execute();
      $stmt2-&gt;bind_result($item);
      while ($stmt2-&gt;fetch()) { //replace with foreach loop?
  ????
  
      }
      }
  </code></pre>
  
  <p>This is where I'm stuck, I want to echo a div for each $list from the first select statement and then use the $dbname returned to issue the second statement.  Inside each $div I would like to put the cooresponding row items like a list.  Any way I could do a foreach loop to do foreach result instead of a while loop?</p>
  
  <p>EDIT: here are pictures of the tables, on separate databases but same server
  example table with info on each list table:
   i.stack.imgur.com/7kEOn.jpg
    example list items table:
  <a href="http://i.stack.imgur.com/XrzoD.png" rel="nofollow">http://i.stack.imgur.com/XrzoD.png</a>
  Thanks For Any Help</p>