Link to home
Create AccountLog in
Avatar of cgcmq
cgcmqFlag for Canada

asked on

Nested Select Query

I need to run 3 MySQL queries each nested within the other.  I can get the 1st & 2nd queries to run but cannot get the 3rd one to work.  Keep getting error on 3rd query: Commands out of sync; you can't run this command now.

I am pretty certain that I have not properly closed one of the previous queries but I have been unable to sort it out myself.

Using PHP 5 & MySQL 5
$resultPicks = $mysqli->query("CALL pTrainingSelectAllCompanies;", MYSQLI_STORE_RESULT);

while($picksRow = $resultPicks->fetch_array(MYSQLI_ASSOC)) {
    // Get Parameter for next SP
    $symbol     = $picksRow['ComanyID'];						    
    
	echo "<ul>  \n\r";
	echo "<li class='company'><a name='" .$picksRow["CompanyURL"] ."'></a>  \n\r";
	echo "<a rel='external' href='http://" .$picksRow["CompanyURL"] ."'>" .$picksRow["CompanyName"] ."</a></li>  \n\r";
	echo "<li class='course'>" .$picksRow["School"] ."</li>  \n\r";
    

    // Free stored results
    clearStoredResults($mysqli);

    // Execute second SP using value from first as a parameter (MYSQLI_USE_RESULT and free result right away)
    $resultData = $mysqli->query("CALL pTrainingSelectCoursesByCompanyID('$symbol')", MYSQLI_USE_RESULT);
    
    while($dataRow = $resultData->fetch_array(MYSQLI_ASSOC)) {
    	// Get Parameter for 3rd & final SP
    	$Course  = $dataRow['CourseID'];
    	
		echo "<li class='Series'>" .$dataRow['CourseName'] ."</li>  \n\r";
		echo "<li class='course'>" .$dataRow['CourseLocation'] ."</li>  \n\r";
		echo "<li class='course'>CourseID: " .$dataRow['CourseID'] ."</li>  \n\r";

	    // Free stored results
	    clearStoredResults($mysqli);
    	
		//This is where everything falls apart.  This query always returns an error:
		//	Commands out of sync; you can't run this command now
		$resultData2 = $mysqli->query("CALL pTrainingSelectSessionsByCourseID('$Course')", MYSQLI_USE_RESULT);
		echo $mysqli->error;
		
		

    }
    echo "</ul>  \n\r\n\r";
    
    $resultData->free(); //worked when here								
}

// Free results from first SP						 
$resultPicks->free(); //worked when here
					
					
$mysqli->close();	
					
#------------------------------------------
function clearStoredResults($mysqli_link){
#------------------------------------------
    while($mysqli_link->next_result()){
      if($l_result = $mysqli_link->store_result()){
              $l_result->free();
      }
    }
}

Open in new window

Avatar of Lukasz Chmielewski
Lukasz Chmielewski
Flag of Poland image

Try to move lines 27,28 to 34,35

          // Free stored results
          clearStoredResults($mysqli);
ASKER CERTIFIED SOLUTION
Avatar of cgcmq
cgcmq
Flag of Canada image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of cgcmq

ASKER

Found the solution on my own.