0

I have a search form that retrieves data from a MySQL database via a filter and show's it in a nice table.

Now I would like to add a "Export to PDF" button to it so I can first filter and then export to pdf the search result.

I know I can use datatables that already have this option but I can't format the output and after some google search I found that I can do it all with dompdf and a template html.

Here is my code

index.php

<?php 
    include "../config.php";
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP My-SQL Search test</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        
        <link href="css/bootstrap-datepicker.css" rel="stylesheet"/>
        <script src="js/bootstrap-datepicker.min.js"></script> 
        <script src="js/bootstrap-datepicker.pt-BR.min.js" charset="UTF-8"></script>
</head>
<body>
    
    <div class="container">
        
            <div class="col-md-12">
                <div class="card mt-5">
                    <div align="center" class="card-header">
                        <h3>Relatorios</h3><br>
                    </div>
                        <form action="#" method="GET">
                            <div class="row">
                                <div class="col-md-2">
                                    <div class="form-group" >
                                        <label>De</label>
                                        <div class="input-group date">
                                        <input type="date" name="from_date" value="<?php if(isset($_GET['from_date'])){ echo $_GET['from_date']; } ?>" class="form-control">
                                    </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Até</label>
                                        <div class="input-group date">
                                        <input type="date" name="to_date" value="<?php if(isset($_GET['to_date'])){ echo $_GET['to_date']; } ?>" class="form-control">
                                    </div>
                                    </div>
                                </div>
                                <div class="row">
                                <div class="col-md-2">
                                    <!-- Dropdown box "Postos" -->
                                    <label>Posto</label>
                         <?php
                              $connect->set_charset("utf8");
                              $result = mysqli_query($connect, "SELECT * FROM postos");
                         ?>
                         <select name="posto" id="posto" class="form-control" placeholder="Escolha uma opção">  
                              <?php
                              while($row = mysqli_fetch_array($result))
                              {
                              echo "<option>$row[nome]</option>";
                              }
                              ?>
                         </select>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Matricula</label>
                                        <div class="input-group date">
                                        <input type="text" name="domain" value="" class="form-control" id="domain" placeholder="AA00AA">
                                    </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Talão</label>
                                        <div class="input-group date">
                                        <input type="text" name="talao" value="" class="form-control" id="talao">
                                        </div>
                                    </div>
                                </div>
                            </div>
                                <div class="col-md-2">
                                    <div class="form-group" align="left"> 
                                     <button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-search"></i> Pesquisar</button>
                                    </div>
                            </div>
                                <div class="col-md-2">
                                    <div class="form-group" align="left">
                                    <a href="index.php" class="btn btn-danger btn-block"><i class="fa fa-refresh"></i> Limpar pesquisa</a></span>
                                </div>
                            </div>
                            <div>
                                <div class="col-md-2">
                                    <div class="form-group" align="left">
                                    <a href="generate-pdf.php" class="btn btn-warning btn-block"><i class="fa fa-refresh"></i> PDF</a></span>

                                </div>
                             </div>
                         </div>
                        </form>
                    </div>
                </div>

                <div class="card mt-4" >
                    <div class="card-body">
                        <table class="table table-borderd">
                            <thead>
                                <tr>  
                                    <th width="15%">Matricula</th>
                                    <th width="20%">Posto</th>
                                    <th width="20%">Data</th>
                                    <th width="15%">Hora</th>
                                    <th width="15%">Talão</th>
                                    <th width="15%">Valor</th>                                
                                </tr>  
                            </thead>
                            <tbody>
                            
                            <?php 
                                 if(isset($_GET['from_date']) && isset($_GET['to_date']) && isset($_GET['domain']))
                                {
                                    $from_date = $_GET['from_date'];
                                    $to_date = $_GET['to_date'];
                                    $domain = $_GET['domain'];
                                    $posto = $_GET['posto'];
                                    $talao = $_GET['talao'];
                                    $query = "SELECT * FROM candidates WHERE  evtdate BETWEEN '$from_date' AND '$to_date' OR domain ='$domain' OR posto = '$posto' OR talao = '$talao'";
                                    $query_run = mysqli_query($connect, $query);
                                    $listvalor = $connect->query($query) or die ($connect->error);
                                    $num_rows = $connect->query($query)->num_rows;
                     //assign results to a variable
                                    $listResults = $connect->query($query) or die($connect->error);
                                    if(mysqli_num_rows($query_run) > 0)
                                    {
                                        foreach($query_run as $row)
                                        {
                                            ?>
                                            <tr>
                                                <td><?php echo $row["domain"]; ?></td>
                                                <td><?php echo $row["posto"]; ?></td>
                                                <td><?php echo $row["evtdate"]; ?></td>
                                                <td><?php echo $row["evttime"]; ?></td>
                                                <td><?php echo $row["talao"]; ?></td>
                                                <td><?php echo $row["valor"]; ?>€</td>
                                                
                                            </tr>
                                           
                                            <?php
                                        }
                                    }
                                    else
                                    {
                                        echo "Não foram encontrados registos";
                                    }
                                }
                            ?>
        </tbody>
    </table>
                <div class="container">
                    <div class="d-flex flex-column align-items-end">
                        <div class="align-self-end">
                   
                        </div>
                    </div>
                </div>                                
        </div>
    </div>
</div>
    <script type="text/javascript">
           $('.to_date').datepicker({
             format: 'dd/mm/yyyy',
             startDate: '-30d',
             language: 'pt-BR'
            });
    </script>
</body>
</html>

This is a "pdf generator" using DOMPDF and a template HTML

generate-pdf.php:

<?php

require __DIR__ . "/vendor/autoload.php";

use Dompdf\Dompdf;
use Dompdf\Options;

$domain = $_POST["domain"];
$posto = $_POST["posto"];

//$html = '<h1 style="color: green">Example</h1>';
//$html .= "Hello <em>$name</em>";
//$html .= '<img src="example.png">';
//$html .= "Quantity: $quantity";

/**
 * Set the Dompdf options
 */
$options = new Options;
$options->setChroot(__DIR__);
$options->setIsRemoteEnabled(true);

$dompdf = new Dompdf($options);

/**
 * Set the paper size and orientation
 */
$dompdf->setPaper("A4", "portrait");

/**
 * Load the HTML and replace placeholders with values from the form
 */
$html = file_get_contents("template.html");

$html = str_replace(["{{ domain }}", "{{ posto }}"], [$domain, $posto], $html);

//$dompdf->loadHtml($html);
$dompdf->loadHtmlFile("template.html");
//$dompdf->loadHtml(html_entity_decode($html));

/**
 * Create the PDF and set attributes
 */
$dompdf->render();

$dompdf->addInfo("Title", "An Example PDF"); // "add_info" in earlier versions of Dompdf

/**
 * Send the PDF to the browser
 */
$dompdf->stream("file.pdf", ["Attachment" => 0]);

/**
 * Save the PDF file locally
 */
$output = $dompdf->output();
file_put_contents("file.pdf", $output);

Now how can I integrate the two?

Thank you all

Xmodpt

Nuno Pires
  • 11
  • 2
  • 1
    code snippets only work for html/css/javascript browser side code. Don't use them for php. `$query = "SELECT * FROM candidates WHERE evtdate BETWEEN '$from_date' AND '$to_date' OR domain ='$domain' OR posto = '$posto' OR talao = '$talao'";` never a better time than the present to **stop wrinting php vulnerable to sql injection**. – erik258 Sep 28 '22 at 21:24
  • thank you for the reply, 1st how do i post the full code the correct way? and in the query how to i stop the injection ? thank you again – Nuno Pires Sep 28 '22 at 21:28
  • Post your code as formatted text. See the [formatting help](https://stackoverflow.com/editing-help). But please do not "_post the full code_". Instead, please re-work your code into a [mre] (the smallest amount of code needed for us to recreate your problem as easily as we reasonably can) and post that, instead. See also [ask] for more general guidance, which may be helpful. – andrewJames Sep 28 '22 at 22:05
  • For your other question, some basic research leads me to this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/q/60174/12567365). I think that should help point you in a good (safer) direction. – andrewJames Sep 28 '22 at 22:06

0 Answers0