<?

// Verifica Sess�o
include "up_verifica_sessao.php";
// Conecta ao servidor e seleciona o banco de dados
include 'up_conexao.php';
mysql_select_db($banco,$conexao);
// variavel que seta a tabela desejada
$tabela = $_POST[tabela];
//se a variavel nao esta setada ainda...
if (!isset($tabela)){
	//...mostra todas as tabelas...
	$sql = "SHOW TABLES FROM company";
	/* where tables_in_company != 'carteira_clientes'
	and tables_in_company != 'carteira_clientes_18_07' */
	$result = mysql_query($sql);
	if (!$result) {
	    echo "DB Error, could not list tables\n";
	    echo 'MySQL Error: ' . mysql_error();
	    exit;
	}	//...numa combobox
	echo 	"<form name='form1' action='exporta.php' method='post'>
				<select name='tabela' id='tabela'>";
	while 	($row = mysql_fetch_row($result)) {
			echo "<option value='$row[0]'>$row[0]
			</option>";
	}
		echo "</select><input type='submit' name='Submit' value='Submit'></form>";
}else{
	// definimos o tipo de arquivo
	header("Content-type: application/msexcel");
	// Como ser� gravado o arquivo com o nome da tabela
	header("Content-Disposition: attachment; filename=$tabela.xls"); 
	echo "<table border='1'> 
		<tr bgcolor='#CCCCCC'>";
	// Faz uma consulta SQL trazendo as linhas referentes ao registros do navegador
	$query = "SELECT * FROM $tabela";
	$query = mysql_query($query,$conexao);
	// gera os cabe�alhos
	$field = mysql_num_fields( $query );
			for ( $i = 0; $i < $field; $i++ ) {       
				$names[] = mysql_field_name( $query, $i );
				echo "<td>".$names[$i]."</td>";       
			}
	echo  "</tr>";
	echo  "<tr>";
	// Gera uma tabela para os registros
	while ($linha = mysql_fetch_array($query)) {
		for ( $i = 0; $i < $field; $i++ ) {
			echo "<td>".$linha[$i]."</td>"; 
		}    
		echo "</tr>";
	}
}
?>