MeekMill
MeekMill

Reputation: 1

Execute a function

I'm trying execute the function excel() and pdf() with a button, but it isn't working.

I just need list the search, and next I need two buttons, one for generate pdf and another for excel.

<?php	

define('FPDF_FONTPATH', 'font/');
require('fpdf.php');
$pdf=new FPDF('p', 'cm', 'A4');
$pdf->Open();
$pdf->AddPage();
$pdf->SetFont('Arial','',12);


include "conexao.php";
      



$busca = $_POST['palavra'];// palavra que o usuario digitou

$busca_query = mysql_query("SELECT * FROM carreteiro WHERE nome LIKE '%$busca%' or cidade like '%$busca%' or estado like '%$busca%' or bairro like '%$busca%' or rua like '%$busca%'")or die(mysql_error());//faz a busca com as palavras enviadas


if (empty($busca_query)) { 
    echo "Nenhum registro encontrado.";
}

// quando existir algo em '$busca_query' ele realizará o script abaixo.
while ($dados = mysql_fetch_array($busca_query)) {
     
    echo "Nome : $dados[nome]<br />"; 
    echo "Cidade: $dados[cidade] <br />";
    echo "Estado: $dados[estado]<br />";
	echo "Rua: $dados[rua]<br />";
	echo "Bairro: $dados[bairro]<br />";
    echo "<hr>";
	
}



//inicio pdf /////////////////////////////////

function pdf(){
	
$exe = mysql_query("SELECT * FROM carreteiro WHERE nome LIKE '%$busca%' or cidade like '%$busca%' or estado like '%$busca%' or bairro like '%$busca%' or rua like '%$busca%'")or die(mysql_error());


while ($dados = mysql_fetch_array($exe))
 {
	$pdf->Cell(3,1,$dados['nome'],1,0,'L');
	$pdf->Cell(4,1,$dados['cidade'],1,0,'L');
	$pdf->Cell(2,1,$dados['estado'],1,0,'L');
	$pdf->Cell(5,1,$dados['rua'],1,0,'L');
	$pdf->Cell(5,1,$dados['bairro'],1,0,'L');
	
 }
	ob_start ();
$pdf->Output();

}


?>

<form action="pdf()"><input type="submit" value="Gerar PDF" /></form>

Upvotes: 0

Views: 36

Answers (1)

halfer
halfer

Reputation: 20439

Change this:

<form action="pdf()"><input type="submit" value="Gerar PDF" /></form>

to this:

<form method="post">
    <input name="submit" type="submit" value="Gerar PDF" />
</form>

In your code, at the appropriate point (I can't quite tell where) you need to add something like the following code. You need to ensure no HTML has been output at this point, since if the PDF is being sent to the browser, you do not want to send a mix of PDF and HTML - it would make no sense.

if ($_POST) {
    pdf();
}

So, this script acts in two ways:

  • When it is visited via get it renders the HTML/form
  • When it is visited via post it creates a PDF

There is probably more work still to do - you probably also need to:

  • Output a PDF content type header
  • exit so no HTML is rendered

Don't forget to address the security vulnerabilities as well - they must not be ignored.

Upvotes: 1

Related Questions