In the majority of cases, you would have two pages. The first page, client-side, makes a call to another page, server-side, and shows a pretty spinning thing while it waits. When the server-side page finishes loading (when your query completes) your first page receives a response and then you can hide the pretty spinning thing to let your user know it's finished.
You can use AJAX - in pure Javascript or a lot simpler in jQuery - to dynamically load some data from your PHP page and show a spinning thingy while it waits. I've used jQuery here.
CSS
#loading_spinner { display:none; }
HTML
<img id="loading_spinner" src="loading-spinner.gif">
<div class="my_update_panel"></div>
jQuery
$('#loading_spinner').show();
var post_data = "my_variable="+my_variable;
$.ajax({
url: 'ajax/my_php_page.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
//Moved the hide event so it waits to run until the prior event completes
//It hide the spinner immediately, without waiting, until I moved it here
$('#loading_spinner').hide();
},
error: function() {
alert("Something went wrong!");
}
});
PHP (my_php_page.php)
<?php
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
// get variable sent from client-side page
$my_variable = isset($_POST['my_variable']) ? strip_tags($_POST['my_variable']) :null;
//run some queries, printing some kind of result
$SQL = "SELECT * FROM myTable";
// echo results
?>