Search code examples
phpmysqlwhile-loopphpword

PHPWord fill .docx template with mysql table data


Thanks for visit my post i'm newbie in php programming and currently i'm trying to make a web application that allows the user to make gas coupons. This is possible thanks to multiple web forms and dynamic options list that store the data in a mysql database. What i'm trying to do is taking the information that will be located into each coupon from the database and replace the variables that i defined into the word template.

Actually the applications allows the user to make one coupon (What it does is take the information from the forms and lists and witha POST method it replace the variables in the php code.)

I really hope somebody could help me because thats all i need to finish my application

Here's a picture of the coupons

Here are my php and html codes.

vales.html

<html>
<head>
<title>Creaci&oacute;n de Vales</title>
<script type="text/javascript" src="dynamicoptionlist.js"></script>
<link rel="icon" type="image/png" href="favicon.png">
<link rel="stylesheet" href="estilos.css">
</head>
<body onLoad="initDynamicOptionLists()">
<header>
<div class="menu">
    <div class="contenedor">
        <div class="logo">
            <a href="index.html">Creaci&oacute;n de vales</a>
        </div>
        <nav>
        <ul>
        <li><a href="index.html">Inicio</a></li>
        <li><a href="altas.html">Creaci&oacute;n de vales</a></li>
        <li><a href="../graph2/index.php">Consulta de gr&aacute;ficas</a></li>
        <li><a href="extras.html">Vales Extras</a></li>
        </ul>
        </nav>
    </div>
</div>
</header>
<center>
    <div class="Shield">
        <img src="shield.png" width="150px" height="150px">
    </div>
<div class="CV">
    <h1>Creaci&oacute;n de Vales</h1>
</div>
<div class="formu">
<form action="template.php" method="post">
<b>Nombre:&nbsp;Presidencia Municipal</b><br><br>
<b>Departamento:</b>
<select name="dpto">
<!--<option value="Default"></option>-->
<option value="Seguridad">Seguridad</option>
<option value="Servicios Primarios">Servicios Primarios</option>
<option value="Ecologia">Ecolog&iacute;a</option>
<option value="Desarrollo Rural">Desarrollo Rural</option>
<option value="Desarrollo Social">Desarrollo Social</option>
<option value="Presidencia">Presidencia</option>
<option value="Fomento Civico">Fomento Civico</option>
<option value="Regidores">Regidores</option>
<option value="Recursos Humanos">Recursos Humanos</option>
<option value="Tesoreria">Tesorer&iacute;a</option>
<option value="Gestoria">Gestor&iacute;a</option>
<option value="Parques y Jardines">Parques y Jard&iacute;nes</option>
<option value="Contraloria">Contralor&iacute;a</option>
<option value="Alumbrado Publico">Alumbrado P&uacute;blico</option>
<option value="Juridico">Jur&iacute;dico</option>
<option value="Obras Publicas">Obras P&uacute;blicas</option>
<option value="Comunicacion Social">Comuniaci&oacute;n Social</option>
<option value="DIF">DIF</option>
<option value="Biblioteca">Biblioteca</option>
<option value="Secretaria del Ayuntamiento">Secretar&iacute;a del Ayuntamiento</option>
<option value="Proteccion Civil">Protecci&oacute;n Civil</option>
<option value="Bomberos">Bomberos</option>
<option value="Turismo Municipal">Turismo Municipal</option>
<option value="Union de Pensionados">Uni&oacute;n de Pensionados</option>
<option value="SEDENA Ejercito Mexicano">SEDENA Ejercito Mexicano</option>
<option value="Instituto de la Juventud">Instituto de la Juventud</option>
<option value="Centro de Salud">Centro de Salud</option>
<option value="Apoyo Cam 10">Apoyo Cam 10</option>
<option value="Apoyo estudiantes Ejido La Cecilia CBTA">Apoyo estudiantes Ejido La Cecilia CBTA</option>
<option value="Apoyo Atencion Medica Oficial de Seguridad">Apoyo Atenci&oacute;n M&eacute;dica Oficial de Seguridad</option>
<option value="Apoyo EMSAD 28 de Agosto">Apoyo EMSAD 28 de Agosto</option>
<option value="Apoyo estudiantes ejido el Durazno">Apoyo estudiantes ejido el Durazno</option>
<option value="Apoyo estudiantes ejido Ganivete">Apoyo estudiantes ejido Ganivete</option>
<option value="Apoyo estudiantes ejido Estacion Madero">Apoyo estudiantes ejido Estaci&oacute;n Madero</option>
</select><br><br>
<b>Responsable:</b>
<select name="rsp">
</select><br><br>
<b>Fecha:</b><br><br>
D&iacute;a:
<input type="text" size="5" placeholder="15" name="dia">&nbsp;&nbsp;
Mes:
<input type="text" size="5" placeholder="9" name="mes">&nbsp;&nbsp;
A&ntilde;o
<input type="text" size="5" placeholder="2015" name="year"><br><br>&nbsp;&nbsp;
<b>Cantidad:</b>
<input type="text" size="5" placeholder="40" name="cantn">&nbsp;&nbsp;&nbsp;&nbsp;
<b>Cantidad Letra:</b>
<input type="text" size="12" placeholder="Cuarenta" name="cantl"><br><br>
<b>Art&iacute;culo:</b>&nbsp;&nbsp;<i>Litros</i>&nbsp;&nbsp;
<b>Importe:</b>
<select name="imp">
    <option>Magna
    <option>Premium
    <option>Diesel
</select>&nbsp;&nbsp;
<b>Precio:<b>
<select name="precio">
</select><br><br>
<b>Seleccione o ingrese Unidad:</b><br><br>
<select name="uni">
</select><br><br>
<input type="text" size="25" placeholder="Camion de pasajeros" name="uni2"><br><br>
<b>Seleccione o ingrese placas:</b><br><br>
<select name="placas">
</select><br><br>
<input type="text" size="12" placeholder="EXO9843" name="placas2"><br><br>
<input type="submit" value="Registrar">&nbsp;&nbsp;&nbsp;
<input type="reset" value="Limpiar Formularios">
</div>
//This is the code for the dynamicoptions select inputs
<script type="text/javascript">
var names = new DynamicOptionList();
var precio = new DynamicOptionList();

precio.addDependentFields("imp","precio");

precio.forValue("Magna").addOptions("13.57");
precio.forValue("Premium").addOptions("14.50");
precio.forValue("Diesel").addOptions("14.2");

names.addDependentFields("dpto","rsp","uni","placas");
names.forValue("Seguridad").addOptions("Lic. xxxxxx xxxxx xxxx","xxxxx xxxxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Servicios Primarios").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Ecologia").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Desarrollo Rural").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Desarrollo Social").addOptions("xxxxx xxxxx xxxxx");
names.forValue("Presidencia").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");
names.forValue("Fomento Civico").addOptions("xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx","xxxxx xxxxx xxxxx");

</script>

template.php

<?php
require_once dirname(__FILE__).'/PHPWord-master/src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();

use PhpOffice\PhpWord\TemplateProcessor;


$total = $_REQUEST[cantn] * $_REQUEST[precio];


$conexion=mysql_connect("localhost","root","") or
  die("Problemas en la conexion");
mysql_select_db("presi",$conexion) or
  die("Problemas en la seleccion de la base de datos");
mysql_query("insert into vales(dpto,rsp,cantn,imp,precio,uni,placas,placas2) values ('$_REQUEST[dpto]','$_REQUEST[rsp]','$_REQUEST[cantn]','$_REQUEST[imp]','$total','$_REQUEST[uni]','$_REQUEST[placas]','$_REQUEST[placas2]')", $conexion) or
  die("Problemas en el select".mysql_error());
mysql_close($conexion);

$templateWord = new TemplateProcessor('plantilla.docx');

//$nombre = $_REQUEST['nombre'];
$folio = $_GET['id'];
$departamento = $_REQUEST['dpto'];
$responsable = $_REQUEST['rsp'];
$dia = $_REQUEST['dia'];
$mes = $_REQUEST['mes'];
$year = $_REQUEST['year'];
$cantn = $_REQUEST['cantn'];
$cantl = $_REQUEST['cantl'];
//$articulo = $_REQUEST['articulo'];
$importe = $_REQUEST['imp'];
$unidad = $_REQUEST['uni'];
$placas = $_REQUEST['placas'];


// --- Asignamos valores a la plantilla
//$templateWord->setValue('nombre',$nombre);
$templateWord->setValue('folio',$folio);
$templateWord->setValue('departamento',$departamento);
$templateWord->setValue('responsable',$responsable);
$templateWord->setValue('dia',$dia);
$templateWord->setValue('mes',$mes);
$templateWord->setValue('year',$year);
$templateWord->setValue('cantn',$cantn);
$templateWord->setValue('cantl',$cantl);
//$templateWord->setValue('articulo',$articulo);
$templateWord->setValue('importe',$importe);
$templateWord->setValue('unidad',$unidad);
$templateWord->setValue('placas',$placas);


// --- Guardamos el documento
ob_clean();
$templateWord->saveAs('Vales.docx');

header("Content-Disposition: attachment; filename=Vales.docx; charset=iso-8859-1");
echo file_get_contents('Vales.docx');
?>

Thaks for the time and sorry for my bad english.


Solution

  • ok - if I understood the question correctly this time, i.e. you need to print out all the coupons into single word file (?) If you were thinking of creating multiple word files for each coupon, then you just need to fetch all the db data and create single word files with the template (as you are already doing), store all the created coupon files somewhere in your server, package the files into single file (zip or something) and serve that file to the user...

    So, for the case of creating the coupons in single word file:

    First, you need to modify your word template a bit: add required template tags (start and end tags that is - named CLONEME in this example) around the area that you wish to clone for each coupon, for example:

    ${CLONEME}
    Here is your normal single coupon template fields, i.e.
    ${folio}
    ${departamento}
    ...
    $(/CLONEME}
    

    And you can process the data insertion into your word template with something like this:

    // first fetch your coupons from the db
    $result = mysql_query("SELECT * FROM vales", $conexion);
    if(!$result) 
    {
        die("Database query failed: " . mysql_error());
    }
    
    // then get your template and clone the coupon block for each of the results
    $templateWord = new TemplateProcessor('plantilla.docx');
    $templateWord->cloneBlock('CLONEME', mysql_num_rows($result));
    
    // loop over your results and fill the template values
    while ($row = mysql_fetch_array($result))
    {
        // NOTE! add the 1 parameter to each setValue so that it replaces only
        // one template field at time (after cloning the block the template
        // contains several same named template fields - for each coupon that is)
        $templateWord->setValue("departamento", $row["dpto"], 1);
        // ... similarly the other values...
    }
    
    // and last, store the word result etc