How to query previous query


#1

Hey guys!

I have part of the following code and I am just wondering whether it is possible to use a previous query? I am not sure whether it is the problem with the {} but I have tried to move my echo statement around but it can’t seem to pick up the $row variables within my $row2 statement? I can’t get $row[‘name’]; to work… or must i query it again?

$sql2 = "SELECT * FROM forum_cats WHERE admin < ?;";
               
              
          	   if(!mysqli_stmt_prepare($stmt, $sql2)) {
		           echo "SQL error";
		        } else {
		          mysqli_stmt_bind_param($stmt, "i", $admin_user_level);
		          mysqli_stmt_execute($stmt);
		          $result2 = mysqli_stmt_get_result($stmt);
		          while ($row = mysqli_fetch_assoc($result2)) {
                   $row = $row['id'];
                  
		          	$sql3 = "SELECT * FROM forum_sub_cats WHERE cid = ?;";
	                  	
	                 if(!mysqli_stmt_prepare($stmt, $sql3)) {
		                echo "SQL error";
		            } else {
		                mysqli_stmt_bind_param($stmt, "i", $row);
		                mysqli_stmt_execute($stmt);
		                $result3 = mysqli_stmt_get_result($stmt);
		                
		                  echo "<option value=\"0\">".$row['name']."</option>\n";
		               	   while ($row2 = mysqli_fetch_assoc($result3)) {
		               	   	  $selected = ($row2['id'] == $id) ? "SELECTED": "";
		               	   	 
			               	   echo "<option value=\"".$row2['id']."\"".$selected.">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$row2['name']."</option>\n";

		               	   }


#2

If you make use of the recommends you have been given in your various help threads, you will have a lot less code, and it will be easier to see the mistakes and in this case avoid the mistake in the first place because you won’t be trying to execute queries inside of loops.

Two things, that you have already been told more than once, that will reduce the above mess to about 6 lines of code (if you were using the much simpler PDO extension) -

  1. Use a single JOIN query to retrieve related data from multiple tables.
  2. Use exceptions to handle database statement errors.

#3

OP doesn’t listen to anybody. You are just wasting your time.