Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] dompdf y MySQL problema

Estas en el tema de dompdf y MySQL problema en el foro de PHP en Foros del Web. Muy buenas. basándome en los ficheros que ha puesto en [URL="http://www.forosdelweb.com/f18/aporte-ejemplo-crear-pdf-haciendo-clic-con-dompdf-919465/"]http://www.forosdelweb.com/f18/aporte-ejemplo-crear-pdf-haciendo-clic-con-dompdf-919465 [/URL] he creado un documento de factura, este, llama datos de MySQL (5 juegos ...
  #1 (permalink)  
Antiguo 19/04/2013, 15:12
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
dompdf y MySQL problema

Muy buenas.
basándome en los ficheros que ha puesto en [URL="http://www.forosdelweb.com/f18/aporte-ejemplo-crear-pdf-haciendo-clic-con-dompdf-919465/"]http://www.forosdelweb.com/f18/aporte-ejemplo-crear-pdf-haciendo-clic-con-dompdf-919465 [/URL] he creado un documento de factura, este, llama datos de MySQL (5 juegos de registro), he puesto el
Código PHP:
Código PHP:
<?php echo $strHTML ?>
y por pantalla sale bien.
he dejado solo el botón de PDF_7 (nombre aleatorio en directorio) y no he modificado el fichero "convertToPDF.php", bueno, he cambiado el directorio pdfs por facturas.
y al dar al botón para imprimir me da el error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
(que genérico....)

y no se por donde puede estar el error...

¿alguna idea?
gracias
__________________
http://www.facebook.com/Punto3Web
  #2 (permalink)  
Antiguo 19/04/2013, 15:13
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 8 meses
Puntos: 1532
Respuesta: dompdf y MySQL problema

el error es claro, ha un error de sintaxis de MySQL, revise las consultas y depure.
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 19/04/2013, 15:13
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: dompdf y MySQL problema

Tu error está en una de tus consultas SQL como ya te dije. Si no colocas tus consultas y el código es muy dificil ayudarte.

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #4 (permalink)  
Antiguo 19/04/2013, 15:15
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

este es el código (parte 1) de emitir_factura.php:
Código PHP:
<?php require_once('../Connections/conexiontienda.php'); 
include(
'../includes/convertToPDF.php'); 
?>
<?php
if (!function_exists('GetSQLValueString')) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ''$theNotDefinedValue ''
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists('mysql_real_escape_string') ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
'text':
      
$theValue = ($theValue != '') ? '"'.$theValue.'"' 'NULL';
      break;    
    case 
'long':
    case 
'int':
      
$theValue = ($theValue != '') ? intval($theValue) : 'NULL';
      break;
    case 
'double':
      
$theValue = ($theValue != '') ? doubleval($theValue) : 'NULL';
      break;
    case 
'date':
      
$theValue = ($theValue != '') ? '"'.$theValue.'"' 'NULL';
      break;
    case 
'defined':
      
$theValue = ($theValue != '') ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

mysql_select_db($database_conexiontienda$conexiontienda);
$query_DatosTienda 'SELECT * FROM tblconstantes';
$DatosTienda mysql_query($query_DatosTienda$conexiontienda) or die(mysql_error());
$row_DatosTienda mysql_fetch_assoc($DatosTienda);
$totalRows_DatosTienda mysql_num_rows($DatosTienda);

if (!
function_exists('GetSQLValueString')) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ''$theNotDefinedValue ''
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists('mysql_real_escape_string') ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
'text':
      
$theValue = ($theValue != '') ? '"'.$theValue.'"' 'NULL';
      break;    
    case 
'long':
    case 
'int':
      
$theValue = ($theValue != '') ? intval($theValue) : 'NULL';
      break;
    case 
'double':
      
$theValue = ($theValue != '') ? doubleval($theValue) : 'NULL';
      break;
    case 
'date':
      
$theValue = ($theValue != '') ? '"'.$theValue.'"' 'NULL';
      break;
    case 
'defined':
      
$theValue = ($theValue != '') ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$varusuario_DatosUsuario '0';
if (isset(
$_GET['usuario'])) {
  
$varusuario_DatosUsuario $_GET['usuario'];
}
mysql_select_db($database_conexiontienda$conexiontienda);
$query_DatosUsuario sprintf('SELECT tblusuario.strNombre, tblusuario.strApellidos, tblusuario.strDni FROM tblusuario WHERE tblusuario.idUsuario = %s'GetSQLValueString($varusuario_DatosUsuario'int'));
$DatosUsuario mysql_query($query_DatosUsuario$conexiontienda) or die(mysql_error());
$row_DatosUsuario mysql_fetch_assoc($DatosUsuario);
$totalRows_DatosUsuario mysql_num_rows($DatosUsuario);

$varCompra_DatosCompra '0';
if (isset(
$_GET['recordID'])) {
  
$varCompra_DatosCompra $_GET['recordID'];
}
mysql_select_db($database_conexiontienda$conexiontienda);
$query_DatosCompra sprintf('SELECT * FROM tblcompra WHERE tblcompra.idCompra = %s'GetSQLValueString($varCompra_DatosCompra'int'));
$DatosCompra mysql_query($query_DatosCompra$conexiontienda) or die(mysql_error());
$row_DatosCompra mysql_fetch_assoc($DatosCompra);
$totalRows_DatosCompra mysql_num_rows($DatosCompra);

$varcompra_DatosLineas '0';
if (isset(
$_GET['recordID'])) {
  
$varcompra_DatosLineas $_GET['recordID'];
}
$varusuario_DatosLineas '0';
if (isset(
$_GET['usuario'])) {
  
$varusuario_DatosLineas $_GET['usuario'];
}
mysql_select_db($database_conexiontienda$conexiontienda);
$query_DatosLineas sprintf('SELECT * FROM tblcarrito WHERE tblcarrito.idUsuario = %s AND tblcarrito.intTransaccionEfectuada = %s ORDER BY tblcarrito.idProducto ASC'GetSQLValueString($varusuario_DatosLineas'int'),GetSQLValueString($varcompra_DatosLineas'int'));
$DatosLineas mysql_query($query_DatosLineas$conexiontienda) or die(mysql_error());
$row_DatosLineas mysql_fetch_assoc($DatosLineas);
$totalRows_DatosLineas mysql_num_rows($DatosLineas);

$varusurio_DatosDireccion '0';
if (isset(
$_GET['usuario'])) {
  
$varusurio_DatosDireccion $_GET['usuario'];
}

$direccionFactura$row_DatosCompra['intFacturacion'];

$varfactura_DatosDireccion '0';
if (isset(
$direccionFactura)) {
  
$varfactura_DatosDireccion $direccionFactura;
}
mysql_select_db($database_conexiontienda$conexiontienda);
$query_DatosDireccion sprintf('SELECT * FROM tbldatoscomprador WHERE tbldatoscomprador.idDireccion = %s AND tbldatoscomprador.relUsuario = %s'GetSQLValueString($varfactura_DatosDireccion'int'),
GetSQLValueString($varusurio_DatosDireccion'int'));
$DatosDireccion mysql_query($query_DatosDireccion$conexiontienda) or die(mysql_error());
$row_DatosDireccion mysql_fetch_assoc($DatosDireccion);
$totalRows_DatosDireccion mysql_num_rows($DatosDireccion);
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
<title>Emisi&oacute;n de factura</title>
<link href='../estilo/twoColFixLtHdr.css' rel='stylesheet' type='text/css' />
__________________
http://www.facebook.com/Punto3Web
  #5 (permalink)  
Antiguo 19/04/2013, 15:16
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

y esta (parte 2):
Código PHP:
</head>

<body>

<div class='container'>
  <div class='contentFactura'>
      <div class='factura'>  
   <?php 
$strHTML 
'<table width="100%" border="0" cellspacing="0" cellpadding="10"><tr>
<td width="39%"><img src="../images/punto3.jpg" width="205" height="76" alt="Logo"></td>
<td width="61%">&nbsp;</td></tr>
<tr><td><strong>Fecha Factura: </strong>'
.date("d-m-Y").' <br />
      <strong>Fecha de compra</strong>: '
.$row_DatosCompra['fchCompra'].'</td>
<td><strong>Factura N&deg;: </strong>AA '
.date("Y").'-'.$row_DatosCompra['idCompra'].'</td></tr>

</table><br>
<table width="100%" border="0" cellspacing="0" cellpadding="2"><tr>
<td width="15%" align="right"><strong>Nombre:</strong></td>
<td width="36%">'
.$row_DatosUsuario['strNombre'].' '.$row_DatosUsuario['strApellidos'].'</td>
<td width="15%" rowspan="7">&nbsp;</td>
<td width="34%"><h2>'
.$row_DatosTienda['strRazonSocial'].'</h2></td></tr>
<tr><td align="right"><strong>D.N.I./C.I.F.:</strong></td>
<td>'
.$row_DatosUsuario['strDni'].'</td>
<td>'
.$row_DatosTienda['strCIF'].'</td></tr>
 <tr><td align="right"><strong>Direcci&oacute;n:</strong></td>
<td>'
.$row_DatosDireccion['strCalle'].', '.$row_DatosDireccion['strNumero'].' '.$row_DatosDireccion['strPiso'].' '.$row_DatosDireccion['strLetra'].'<br />'.$row_DatosDireccion['strExtension'].'</td>
 <td>'
.$row_DatosTienda['strCalle'].', '.$row_DatosTienda['strNumero'].' '.$row_DatosTienda['strPiso'].' '.$row_DatosTienda['strLetra'].'<br />'.$row_DatosTienda['strExtension'].'</td></tr>
<tr><td align="right"><strong>Poblaci&oacute;n:</strong></td>
<td>'
.$row_DatosDireccion['strPoblacion'].'</td>
<td>'
.$row_DatosTienda['strPoblacion'].'</td></tr>
<tr><td align="right"><strong>C.P.:</strong></td>
<td>'
.$row_DatosDireccion['intCP'].'</td>
<td>'
.$row_DatosTienda['intCP'].'</td></tr>
<tr><td align="right"><strong>Provincia:</strong></td>
<td>'
.MostrarNombreProvincia($row_DatosDireccion['intProvincia']).'</td>
<td>'
.MostrarNombreProvincia($row_DatosTienda['intProvincia']).'</td></tr>
<tr><td align="right"><strong>Pais:</strong></td>
<td>'
.MostrarNombrePais($row_DatosDireccion['intPais']).'</td>
<td>'
.MostrarNombrePais($row_DatosTienda['intPais']).'</td></tr></table><br><br>
<table border="0" cellspacing="0" cellpadding="3">
<tr align="center">
<td><strong>Marca</strong></td>
<td><strong>Producto</strong></td>
<td><strong>Color</strong></td>
<td><strong>Talla</strong></td>
<td><strong>Precio</strong></td>
<td><strong>Cant.</strong></td>
<td><strong>Dto.</strong></td>
<td><strong>Total</strong></td>
<td colspan="2"><strong>I.V.A.</strong></td>
<td><strong>Total Linea</strong></td></tr>'
;
     do { 
   if (
$row_DatosLineas['idProducto']!=90000){
   
//*********** VARIABLES ************
//    *********************************************
                
$precioTicket=0;
                
                     
$descuentoEnLinea=($row_DatosLineas['intCantidad']*$row_DatosLineas['intPrecioUnitario']/100)*$row_DatosCompra['intDescuento'];
                     
$TotalLinea=$row_DatosLineas['intCantidad']*$row_DatosLineas['intPrecioUnitario']-$descuentoEnLinea
                     
$IVALinea=$TotalLinea*$row_DatosLineas['intIVA'];
                     
$IVA=$row_DatosLineas['intIVA']*100;
    
//*********** VARIABLES ************
//    *********************************************

$strHTML $strHTML '<tr><td align="left">'.ObtenerNombreMarcadeProducto($row_DatosLineas['idProducto']).'</td>
<td align="left">'
.ObtenerNombreProducto($row_DatosLineas['idProducto']).'</td>
<td align="center">'
.ObtenerNombreTalla($row_DatosLineas['intColor']).'</td>
<td align="center">'
.ObtenerNombreTalla($row_DatosLineas['intTalla']).'</td>
<td align="right">'
.$row_DatosLineas['intPrecioUnitario'].'€</td>
<td align="center">'
.$row_DatosLineas['intCantidad'].'</td>
 <td align="center">'
.$row_DatosCompra['intDescuento'].'%</td>
<td align="right">'
.round($TotalLinea,2).'€</td>
<td >'
.$IVA.'%</td>
<td align="right">'
.round($IVALinea,2).'€</td>
<td align="right">'
.round($TotalLinea+$IVALinea,2).'€</td></tr>';
       }
               else
              { 
              
//CONTROLAMOS EL TICKET DE DESCUENTO 
               
$precioTicket=$row_DatosLineas['dblTicket'];
      
$strHTML $strHTML '<tr><td>&nbsp;</td>
                <td>Ticket Descuento</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td align="right">-'
.$row_DatosLineas['dblTicket'].'€</td>';
      
        
//FIN DE CONTROLAMOS EL TICKET DE DESCUENTO
               
}
     } while (
$row_DatosLineas mysql_fetch_assoc($DatosLineas));

$strHTML $strHTML '</table><br><br>
<br /><br /><br />
<table border="0" align="right" cellpadding="4" cellspacing="0"><tr>
<td align="right"><strong>Sub-Total:</strong></td>
 <td align="right">'
.$row_DatosCompra['dblSubTotal'].'€</td></tr>
 <tr><td align="right"><strong>Total I.V.A.:</strong></td>
<td align="right">'
.$row_DatosCompra['dblTotalIVA'].'€</td></tr>
<tr><td align="right"><strong>Gastos de env&iacute;o:</strong></td>
 <td align="right">'
.$row_DatosCompra['dblGastosEnvio'].'€</td></tr>';

  if (
$precioTicket>0) {
  
$strHTML $strHTML '<tr><td align="right"><strong>Ticket Dto.:</strong></td>
<td align="right">-'
.$precioTicket.'€</td></tr>';
      }
  
$totalFactura=$row_DatosCompra['dblTotal']-$precioTicket;
$strHTML $strHTML '<tr><td align="right"><strong>TOTAL:</strong></td>
<td align="right">'
.$totalFactura.'€</td></tr></table>';



if ( isset(
$_POST['PDF_7']) ) 
    
doPDF("",$strHTML,true,"style.css",true); //lo guardamos en la carpeta pdfs 
    
?>
<!doctype html> 
<html> 

<head> 
</head> 
<body>     
        
<?php echo $strHTML ?>
 <!-- end .contentfactura --></div>
   <!-- end .content --></div>
  <div class='footer'>
    <p><div class="formulario">
<form  action='<?php echo $_SERVER['PHP_SELF'?>' method='POST'> 
<input name='PDF_7' type='submit' value='CREAR FACTURA' />

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



<!-- ***************** PENDIENTE DE PONER EN FACTURA *************************** -->
<div class='Lineafactura'>
<?php    
$strHTML 
$strHTML '<table border="0" align="center" cellpadding="0" cellspacing="0"><tr>
<td><strong>E-Mail:&nbsp;</strong></td>
<td>'
.$row_DatosTienda['strEmail'].'&nbsp;</td>
<td><strong>Telefono:&nbsp;</strong></td>
<td>'
.$row_DatosTienda['strTelefono'].'&nbsp;</td>
<td> <strong>Fax:&nbsp;</strong></td>
<td>'
.$row_DatosTienda['strFax'].'</td></tr></table>';
?>
</div>
  </div>
<!-- end .container --></div>
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result
($DatosTienda);

mysql_free_result($DatosUsuario);

mysql_free_result($DatosCompra);

mysql_free_result($DatosLineas);

mysql_free_result($DatosDireccion);
?>
__________________
http://www.facebook.com/Punto3Web
  #6 (permalink)  
Antiguo 19/04/2013, 15:21
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

__________________
http://www.facebook.com/Punto3Web

Última edición por pdominguez0608; 19/04/2013 a las 15:28
  #7 (permalink)  
Antiguo 19/04/2013, 15:34
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

Cita:
Iniciado por maycolalvarez Ver Mensaje
el error es claro, ha un error de sintaxis de MySQL, revise las consultas y depure.
pero no entiendo porque en pantalla sale bien (ver imagen)
__________________
http://www.facebook.com/Punto3Web
  #8 (permalink)  
Antiguo 19/04/2013, 15:36
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

y este es el código de convertToPDF.php

Código PHP:
<?php 
/*----------------------------------------------------------/* 
     
$path     : nombre y/o ruta del pdf (sin la extensión) 
                p.e: --> 'ejemplo' , 'pdfs/nuevo-ejemplo' 
                si se deja vacío --> se genera uno aleatorio 

$content  : contenido del pdf 

$body     : true o false. 
                true  --> Añade; <doctype>, <body>, <head> a $content 
                false --> no altera el $content 
                 
$style    : la ruta de la CSS. Puede estar vacía 
                 Para cargar una css --> necesita $body = true; 

$mode     : true o false. 
                true  --> guarda el pdf en un directorio y lo muestra  
                false --> pregunta si guarda o abre el archivo  
             
$paper_1  : tamaño del papel[*] 
$paper_2  : estilo del papel[*] 
     [*] como ver las opciones disponibles:  
        --> http://code.google.com/p/dompdf/wiki/Usage#Invoking_dompdf_via_the_command_line 

/*----------------------------------------------------------*/  

require_once('../dompdf/dompdf_config.inc.php'); 

function 
doPDF($path='',$content='',$body=false,$style='',$mode=false,$paper_1='a4',$paper_2='portrait'
{     
    if( 
$body!=true and $body!=false $body=false
    if( 
$mode!=true and $mode!=false $mode=false
     
    if( 
$body == true 
    { 
        
$content=
        <!doctype html> 
        <html> 
        <head> 
            <link rel="stylesheet" href="'
.$style.'" type="text/css" /> 
        </head> 
        <body>' 
            
.$content
        
'</body> 
        </html>'

    } 
     
    if( 
$content!='' 
    {         
        
//Añadimos la extensión del archivo. Si está vacío el nombre lo creamos 
        
$path!='' $path .='.pdf' $path crearNombre(10);   

        
//Las opciones del papel del PDF. Si no existen se asignan las siguientes:[*] 
        
if( $paper_1=='' $paper_1='a4'
        if( 
$paper_2=='' $paper_2='portrait'
             
        
$dompdf =  new DOMPDF(); 
        
$dompdf -> set_paper($paper_1,$paper_2); 
        
$dompdf -> load_html(utf8_encode($content)); 
        
ini_set("memory_limit","128M"); //opcional  
        
$dompdf -> render(); 
         
        
//Creamos el pdf 
        
if($mode==false
            
$dompdf->stream($path); 
             
        
//Lo guardamos en un directorio y lo mostramos 
        
if($mode==true
            if( 
file_put_contents($path$dompdf->output()) ) header('Location: '.$path); 
    } 


function 
crearNombre($length

    if( ! isset(
$length) or ! is_numeric($length) ) $length=6
     
    
$str  "0123456789abcdefghijklmnopqrstuvwxyz"
    
$path ''
     
    for(
$i=$i<$length $i++) 
      
$path .= $str{rand(0,strlen($str)-1)}; 

    return 
'../documentos/facturas/'.$path.'_'.date("Ymd").'.pdf';     


?>
__________________
http://www.facebook.com/Punto3Web
  #9 (permalink)  
Antiguo 22/04/2013, 14:53
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

Muy buenas, de nuevo.
he vuelto a hacer las consultas, y la tabla con los datos. hasta aquí sale bien por pantalla. He pasado los datos de la Pero en el momento que paso los datos de la tabla a la variable ($strHTML) y hago el echo de la variable y sale bien también.
pero al pulsar el botón que envía el formulario es cuando da el error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"

este mismo código, lo he probado con algo mas sencillo y funciona...
¿alguna pista por donde atacar?
gracias
__________________
http://www.facebook.com/Punto3Web
  #10 (permalink)  
Antiguo 24/04/2013, 03:13
Avatar de pdominguez0608  
Fecha de Ingreso: enero-2013
Ubicación: Alcobendas
Mensajes: 40
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: dompdf y MySQL problema

Mas pruebas, he pasado el código para crear el pdf a la pagina emitir_factura.php y aquí si funciona, debe haber algún problema al hacer el "submit" a convertPDF.php
pero no veo el que, he copiado las consultas a esta pagina y tampoco

¿alguna ayuda?
gracias a todos
__________________
http://www.facebook.com/Punto3Web

Etiquetas: dompdf, html, mysql, registro, sql
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:08.