title: where to put while loop with mysqli fetch?
body: <p>I am using mysqli and php to be able to select a column from the database and to also be able to insert data into the database. Now while researching mysqli, I have found out that before checking to see if the number of rows equals to 0, I need to include a <code>while($stmt-&gt;fetch()) {</code> </p>
  
  <p>Now because I have to blocks of code, one for SELECT and other INSERT, I want to know that does the while fetch loop suppose to wrap round the whole code or does it suppose to wrap round the SELECT block of code and INSERT block of code separately?</p>
  
  <p>UPDATE:</p>
  
  <pre><code>    $query = "SELECT TeacherAlias FROM Teacher WHERE TeacherAlias = ?";
         // prepare query
         $stmt=$mysqli-&gt;prepare($query);
         // You only need to call bind_param once
         $stmt-&gt;bind_param("s",$getid);
         // execute query
         $stmt-&gt;execute();
         // get result and assign variables (prefix with db)
         $stmt-&gt;bind_result($dbTeacherAlias);
         //get number of rows
         $stmt-&gt;store_result();
         $numrows = $stmt-&gt;num_rows();
         $results = $stmt-&gt;fetch_all();
  
  
      foreach ($results as $row) {
         if ($numrows == 0){    
  
             // don't use $mysqli-&gt;prepare here
         $query = "SELECT TeacherUsername FROM Teacher WHERE TeacherUsername = ?";
         // prepare query
         $stmt=$mysqli-&gt;prepare($query);
         // You only need to call bind_param once
         $stmt-&gt;bind_param("s",$getuser);
         // execute query
         $stmt-&gt;execute(); 
         // get result and assign variables (prefix with db)
         $stmt-&gt;bind_result($dbTeacherUsername);
         //get number of rows
         $stmt-&gt;store_result();
         $numrows = $stmt-&gt;num_rows();
         $results = $stmt-&gt;fetch_all();
      }
  
  foreach ($results as $row) {  
         if ($numrows == 0){
                                                 // don't use $mysqli-&gt;prepare here
         $query = "SELECT TeacherEmail FROM Teacher WHERE TeacherEmail = ?";
         // prepare query
         $stmt=$mysqli-&gt;prepare($query);
         // You only need to call bind_param once
         $stmt-&gt;bind_param("s",$getemail);
         // execute query
         $stmt-&gt;execute(); 
         // get result and assign variables (prefix with db)
         $stmt-&gt;bind_result($dbTeacherEmail);
         //get number of rows
         $stmt-&gt;store_result();
         $numrows = $stmt-&gt;num_rows();
         $results = $stmt-&gt;fetch_all();
  }
  
  }
  }
  }
  </code></pre>