run Function

Asked

Viewed 118 times

2

I would like to execute the following functions, excel() which generates the excel file, and the function pdf(), these files are generated within a search, however I can not run through buttons, and as they are generated automatically, I decided to create Function to be able to run, but it did not work very well, someone could help me?

<?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>

2 answers

0

This really doesn’t work.

The problem is that PHP is a language run within the server, and HTML, as well as Javascript, are "client languages". Therefore, it is not possible to call PHP methods directly from the client.

What you should do is at action put the address of script which will generate the report, and specify the desired format. In script Report generation PHP, you then decide and execute the appropriate method (to generate Excel or PDF).

Simply put, it would be something like:

index php.

<form action="relatorio-pdf.php" method="post">
    <input type="text" name="palavra" />
    <input type="submit" value="Gerar PDF" />
</form>

relatorio-pdf.php

<?php
    // tentei adaptar seu código para tornar o exemplo mais concreto.
    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
    $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();

Note that this code simply generates the PDF. Generating HTML and XLS can be separate codes or you can modify this example to support all this in a single code.

I hope I helped clear up your ideas a bit.

Editing

PHP needs to somehow know what the word is to perform the search. In the example I created, I followed your code that expects a parameter POST with the name palavra.

The flow of a normal application is as follows:

  1. Displays a page asking the user to enter the word for the search;
  2. Displays a page with the search results, and buttons to export the desired PDF results (or any other format).

I’ll illustrate how you could build this:

The item 1 would be built in the archive busca.php; the search would be performed and displayed in the file resultado.php; export to PDF file exportar-pdf.php.

Note, I will show only the interesting parts of HTML.

php search.

<form action="resultado.php" method="post">
    <input type="text" name="palavra" />
    <input type="submit" value="Buscar" />
</form>

php result.

This file follows what you developed yourself, but without the PDF part:

<?php   
    define('FPDF_FONTPATH', 'font/');

    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>";
    }
?>
<form action="exportar-pdf.php">
    <input type="hidden" name="palavra" value="<?php echo $busca; ?>" />
    <input type="submit" value="Gerar PDF" />
</form>

Notice that inside the form, added a hidden field with the name palavra, initialized with the previously typed search word. This way, we can pass it to the script that will export the PDF search data.

export-pdf.php

<?php
    // tentei adaptar seu código para tornar o exemplo mais concreto.
    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
    $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();

Note that the code of this file, is exactly the code I put earlier!

Completion

This way, we have the full application flow. I haven’t checked if your queries are correct. Without the bank’s DDL, it’s tricky to do this, and apparently, that’s not the problem.

The solution by AJAX posted in another answer, is also option. However, I recommend that you first do it this way, which is simpler by requiring only knowledge in PHP. The AJAX solution requires Javascript knowledge, and does not exclude PHP knowledge, so better before consolidating in the simplest way, and then moving on to the most complex implementation (and in this case not so complex and much better!).

I hope I’ve helped.

  • Thank you very much friend, it worked. but it remains appearing the search field, as I do not understand, have to remove the field where I search? código <input type="text" name="word" /> código

  • I looked again, and this being generated pdf of all database data, not only the search :/

  • Yes, just remove the field. As I said, I modified your code only to give a starting point. I will add more information to the answer.

  • thanks for the attention, I managed to execute but persists in the same, it does not filter the word and ends up pulling all the data from the database

  • This is another problem, unlike running a PHP call. I recommend you to open a new question just for him, and inform your table structure, data example, etc.

  • 1

    thanks in advance for the help, thank you very much.

Show 1 more comment

0

php does not work that way, with javascript you could do, but with php you need to reload the page or use jQuery AJAX

Your form has to send a POST or GET with the information that php needs to execute the function, example:

<form>
<input type="hidden" name="comando" value="pdf" />
<input type="submit" value="Gerar PDF" />
</form>

Already in php you would do the following:

<?php
$comando = $_GET["comando"];

if ($comando == "pdf") {
   pdf(); // chama a função aqui
}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.