Translate

quarta-feira, 19 de setembro de 2012

Realizar consultas MS SQL 2008 através de PHP



  1. Instalar pré-requisitos:
    apt-get install apache2 php5 libapache2-mod-php5 php5-mssql unixodbc unixodbc-dev freetds-dev tdsodbc freetds-bin
    
  2. Configurar /etc/freetds/freetds.conf, adicionando:
    [tds]
    host = IP_DO_SERVIDOR_MSSQL
    port = 1433
    tds version = 8.0 #Porta padrão para MSSQL
    client charset = UTF-8
    
  3. Configurar /etc/odbcinst.ini, adicionando:
    [tds]
    Description     = FreeTDS Driver for Linux & MSSQL on Win32
    Driver          = /usr/lib/odbc/libtdsodbc.so
    Setup           = /usr/lib/odbc/libtdsS.so
    UsageCount      = 1
    
  4. Configurar /etc/odbc.ini, adicionando:
    [tds]
    Description = Test to freeTDS
    Driver = tds
    Trace = No
    Database = BANCO_DE_DADOS
    Server = IP_DO_SERVIDOR_MSSQL
    Port = 1433 #Porta padrão para MSSQL
    
  5. Testar a conexão:
    isql -v tds USUARIO_DO_DB PASS_DO_DB
    #retornará: o prompt SQL "SQL>"
    
  6. Ativar o módulo ODBC em PHP5 (/etc/php5/apache2/php.ini), adicionando:
    extension = odbc.so
    
  7. Reiniciar o Apache:
    /etc/init.d/apache2 restart
    
  8. Testar a consulta em PHP, criando um script PHP como o seguinte:
    <?php
    //teste_de_coexao.php
    
    echo "<table>";
    $link = mssql_connect('IP_DO_SERVIDOR_MSSQL', 'USUARIO_NO_DB', 'PASS_NO_DB');
    
    if (!$link) {
       die('Unable to connect!');
    }
    
    if (!mssql_select_db('BANCO_DE_DADOS', $link)) {
       die('Unable to select database!');
    }
    
    $result = mssql_query('SELECT * FROM TABELA');
    
    while ($row = mssql_fetch_array($result)) {
       echo "<tr><td>NA: " . $row['numero'] . "/" . $row['ano'] . "</td><td> Solicitante: " . $row['solicitante'] . "</td></tr>";
    }
    
    echo "</table>";
    mssql_free_result($result);
    ?>
    

Acesse o site para verificar se o resultado esperado foi retornado.


Se tiver problemas com charset:
http://www.rafaeltheodoro.com.br/php/converter-codificacao-do-sqlserver-para-o-mysql-em-php-charset-cp850-do-sqlserver-para-mysql/comment-page-1/


segunda-feira, 10 de setembro de 2012

TestLink: exportar relatório HTML para PDF / export report to PDF



Habilitar formato / Enable Format

a. testlink/cfg/reports.cfg.php - habilitar formato: descomentar "FORMAT_PDF => 'format_pdf" (linha 44); / enable format: uncomment "FORMAT_PDF => 'format_pdf" (line 44);
b. testlink/cfg/reports.cfg.php - habilitar formato em cada tipo de relatório: adicionar "format_pdf" em "format" dos tipos de relatórios do qual habilitaremos a saída em PDF (atualmente habilitado nas linhas 79 e 85); enable format in each report type: add "format_pdf" in "format" of the types of reports which habilitaremos the PDF output (I enabled only in 79 and 85);
c. testlink/testlink/lib/results/printDocument.php - se o relatório for em PDF, redirecionar para o conversor: altere as seguintes linhas (262-270): / if the report is in PDF, redirect to the converter: change the following lines (262-270):
// add application header to HTTP
if (($args->format == FORMAT_ODT) || ($args->format == FORMAT_MSWORD))
{
    flushHttpHeader($args->format, $doc_info->type);
}
// send out the data
echo $generatedText;

Para / To:
// add application header to HTTP 
if (($args->format == FORMAT_ODT) || ($args->format == FORMAT_MSWORD))
{
        flushHttpHeader($args->format, $doc_info->type);

} else if ($args->format == FORMAT_PDF) { // ********* Saída do relatório em PDF *********

        //Enviar HTML para DOMPDF, via POST (converter html > pdf) / Send HTML to DOMPDF via POST (convert html> pdf)
        echo "<form action='dompdf/conversor.php' method='post' name='frm'>";
                //Enviar via POST o relatório em HTML para conversão ($PDF) e o nome do documento PDF ($_SESSION['testprojectName']) / Send the POST report to HTML conversion ($ PDF) and the name of the PDF document ($ _SESSION ['testprojectName'])
                echo "<input type='hidden' name='html' value='" . base64_encode(serialize($PDF)) . "'>
                      <input type='hidden' name='projectname' value='" . $_SESSION['testprojectName'] . "'>
                ";
        echo "
                </form>
                <script language=\"JavaScript\">
                        document.frm.submit();
                </script>
        ";

} else {
        // send out the data (!=PDF)
        echo $generatedText;
}

Observações: a variável "$generatedText" recebe o relatório em HTML, para depois exibir través de "echo $generatedText;" (PHP). Para o relatório em PDF, não é interessante que a primeira página e o HTMLHeader sejam exibidos, portanto utiliza-se a variável "$PDF" para receber paralelamente todos os valores tal como "$generatedText", exclusive:
Notes: The variable "$ generatedText" receives the report in HTML to display after abeam of "echo $ generatedText;" (PHP). For the PDF report, is not it interesting that the first page to appear HTMLHeader and therefore uses the variable "$ PDF" to receive all parallel values ​​such as "$ generatedText 'exclusive:
//Linhas / Lines 216-217
//$PDF = renderHTMLHeader($doc_info->type.' '.$doc_info->title,$_SESSION['basehref']); //Desativado / Disable
//$PDF .= renderFirstPage($doc_info); //Desativado / Disable

Valores recebidos pela variável / Amounts received by the variable:
//Linhas / Lines 231-232
$PDF .= renderSimpleChapter(lang_get('scope'), $doc_info->tproject_scope);
$PDF .= renderTestSpecTreeForPrinting($db, $tree, $doc_info->content_range,$printingOptions, null, 0, 1, $args->user_id);

//Linha 242
$PDF .= renderSimpleChapter(lang_get('scope'), $doc_info->testplan_scope);

//Linha 247
$PDF .= renderTestPlanForPrinting($db, $tree, $doc_info->content_range,$printingOptions,null,0,1, $args->user_id,$args->tplan_id,$args->tproject_id);

//Linha 253
$PDF .= buildTestPlanMetrics($doc_data->statistics);

d. testlink/lib/results/dompdf/conversor.php - gera código para executar a conversão através do plugin dompdf:
testlink/lib/results/dompdf/conversor.php - generates code to perform the conversion using the dompdf plugin:
<?php
//Invoca o conversor / Invoke the converter
require_once("dompdf_config.inc.php");
//Recebe o relatório em HTML / Get the HTML report
$html = utf8_decode(unserialize(base64_decode($_POST["html"])));
$dompdf = new DOMPDF();
//Indica o que converter / Indicates that convert
$dompdf->load_html($html, 'UTF-8');
$dompdf->set_paper('a4', 'portrait');
$dompdf->render();
//Disponibiliza o relatório / Provides the report
$dompdf->stream($_POST['projectname'] . ".pdf");
?>