Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] PHP OO No graba registros en base de datos

Estas en el tema de No graba registros en base de datos en el foro de PHP en Foros del Web. Buenas, tengo un programa de facturación en el cual estoy ingresando varios registros a la vez con mysqli pero el programa corre sin errores pero ...
  #1 (permalink)  
Antiguo 28/08/2015, 17:21
 
Fecha de Ingreso: junio-2015
Mensajes: 5
Antigüedad: 8 años, 9 meses
Puntos: 0
No graba registros en base de datos

Buenas,
tengo un programa de facturación en el cual estoy ingresando varios registros a la vez con mysqli pero el programa corre sin errores pero cuando reviso mi base de datos no tengo nada.
ya llevo varios dias viendo que pasa pero me supera ya no se que probar

aca va la pagina edita.php

<?php

include('libreria/motor.php');

if($_POST){
$factura = new factura();
$factura->id = 0;
$factura->rnc = $_POST['txtRNC'];
$factura->ncf = $_POST['txtNCF'];
$factura->cliente = $_POST['txtCliente'];
$factura->fecha = $_POST['txtFecha'];
$factura->concepto = $_POST['txtConcepto'];
$factura->subtotal = $_POST['txtSubTotal'];
$factura->impuestos = $_POST['txtImp'];
$factura->total = $_POST['txtTotal'];

$factura->guardar();
}

$titulo = "Nueva Factura";
include('plantilla.php');

?>
<style>
#divTotales{
float:right;
border:dashed #000000 1px;
}
</style>
<form method="post" action="editar.php">
<table>
<tr>
<th>Cliente</th>
<td><input type="text" name="txtCliente"/></td>
<th>Fecha</th>
<td><input type="text" name="txtFecha"/></td>
</tr>
<tr>
<th>RNC</th>
<td><input type="text" name="txtRNC"/></td>
<th>NCF</th>
<td><input type="text" name="txtNCF"/></td>
</tr>
</table>
<fieldset>
<legend>Concepto</legend>
<textarea class='tblDaata' name="txtConcepto"></textarea>
</fieldset>
<button type='button' onclick="nuevoArticulo();">Add</button>
<table class='tblData'>
<thead>
<tr>
<th>Codigo</th>
<th>Articulo</th>
<th>Cantidad</th>
<th>Precio</th>
<th>Subtotal</th>
<th>act</th>
</tr>
</thead>
<tbody id="tbDetalle">

</tbody>
</table>

<div style="height:150px;">
<button type="submit">Guardar</button>
<button type="button" onClick="cancelar();">Cancelar</button>
<button type="button">Nuevo</button>
<button type="button">Imprimir</button>
<div id="divTotales">
<table>
<tr>
<th>Sub Total:</th>
<td>
<input type="text" name="txtSubTotal" id="txtSubTotal"/>
</td>
</tr>
<tr>
<th>Impuestos:</th>
<td>
<input type="text" name="txtImp" id="txtImp"/>
</td>
</tr>
<tr>
<th>Total:</th>
<td>
<input type="text" name="txtTotal" id="txtTotal"/>
</td>
</tr>
</table>
</div>
</div>
</form>
<script>

function crearCampo(nombre){
td = document.createElement('td');
txt = document.createElement('input');
txt.type = 'text';
txt.setAttribute('name',nombre);
td.appendChild(txt);
return td;
}

function nuevoArticulo(){
destino = document.getElementById('tbDetalle');
tr = document.createElement('tr');
tr.appendChild(crearCampo('det_codigo[]'));
tr.appendChild(crearCampo('det_articulo[]'));
tr.appendChild(crearCampo('det_cantidad[]'));
tr.appendChild(crearCampo('det_precio[]'));
tr.appendChild(crearCampo('det_subtotal[]'));
td = document.createElement('td');
x = document.createElement('button');
x.type='button';
x.innerHTML = 'X';
x.setAttribute('onclick','eliminarFila(this)');
td.appendChild(x);
tr.appendChild(td);
destino.appendChild(tr);
}

function eliminarFila(btn){
if(confirm("Seguro Quiere Borrar la fila?")){
fila = btn.parentNode.parentNode;
fila.parentNode.removeChild(fila);
}
}

function cancelar(){
ok = confirm("Seguro que quiere Cancelar");
if(ok){
window.location = './';
}
}
</script>


y aca va la pagina ok_factura.php que supuestamente inserta los datos creados..

<?php

class factura{

private $id = '';
private $concepto = '';
private $cliente = '';
private $fecha = '';
private $rnc = '';
private $ncf = '';
private $subtotal = '';
private $impuestos = '';
private $total = '';
private $ci = '';

private $detalleFactura;

public function agregarDetalle($codigo, $articulo, $cantidad, $precio){
$this->detalleFactura[] = array(
'codigo'=>$codigo,
'articulo'=>$articulo,
'cantidad'=>$cantidad,
'precio'=>$precio,
'subtotal'=>$cantidad * $precio
);
}

function __construct(){
$this->detalleFactura = array();
}

function __get($prop){

if(isset($this->$prop)){
return $this->$prop;
}
else{
echo "La propiedad {$prop} no existe en la factura";
}
return "";
}

function __set($prop, $val){

if(isset($this->$prop)){
$this->$prop = $val;
}
else{
echo "La propiedad {$prop} no existe en la factura";
}
}

function guardar(){
$this->ci = count($this->detalleFactura);

$con = objCon::obtenerInstancia();
if ($this->id >0){
//Actualizar
}else{
//Insertar

$sql = "INSERT INTO `factura`
('concepto', 'cliente', 'fecha', 'rnc', 'ncf', 'subtotal', 'impuestos', 'total', 'ci')
VALUES
({$this->concepto}',
'{$this->cliente}',
'{$this->fecha}',
'{$this->rnc}',
'{$this->ncf}',
'{$this->subtotal}',
'{$this->impuestos}',
'{$this->total}',
'{$this->ci}');";
mysqli_query($con, $sql);
$this->id = mysqli_insert_id($con);

}

//foreach($this->detalleFactura as $detalle){
//}//

}
}





?>
  #2 (permalink)  
Antiguo 28/08/2015, 20:58
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 15 años, 11 meses
Puntos: 2534
Respuesta: No graba registros en base de datos

Cita:
pero el programa corre sin errores
Ajá, ¿y cómo verificaste eso para tener la certeza?

Que no salga error en pantalla no quiere decir que todo sea perfecto.

¿Y si vas depurando todo tu código linea por linea para ver si realmente se ejecuta como esperas?
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 28/08/2015, 21:31
 
Fecha de Ingreso: junio-2015
Mensajes: 5
Antigüedad: 8 años, 9 meses
Puntos: 0
Respuesta: No graba registros en base de datos

1.- En ok_factura.php

en la funcion guardar

function guardar(){
$con = objCon::obtenerInstancia();
if ($this->id >0){
//Actualizar
}else{
//Insertar
echo $this->id;

le hice un echo al $this->id para ver si era cero como debía o estaba toamando otro valor y por eso no cargaba datos en mi base de datos..

2.- al final de la funcion guardar

mysqli_query($con, $sql);
$this->id = mysqli_insert_id($con);
echo $sql;

le hice un echo a $sql para ver que datos tenia el arreglo

pero al dar guardar pasa volado sin errores como si todo estuviera ok y me muestra en pantalla

0INSERT INTO `factura` ('concepto', 'cliente', 'fecha', 'rnc', 'ncf', 'subtotal', 'impuestos', 'total', 'ci') VALUES ( 'probando fact', 'Amadis', '', '454546212', 'AE000000012', '100', '10', '110', '');

claro el primer cero es el valor del Id y el resto el valor de $sql

pero sigue sin grabar datos en mi base de datos "facil" que al parecer no lo es tanto...


tienes razon en eso de que si no muestra error en pantalla no significa que no tenga error... tambien he probado con hacer un require_oncee en editar.php

include('libreria/motor.php');
require_once('libreria/conexion.php');

un require _once para bypasear el include... (lo que abunda no daña pense...)

en fin he intentado hacer varias pruebas pero nada me resulta... por eso he acudido a ustedes que tienen muchísima mas experiencia que yo...


gracias por responder
  #4 (permalink)  
Antiguo 28/08/2015, 21:38
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 15 años, 11 meses
Puntos: 2534
Respuesta: No graba registros en base de datos

Igual si le dieras formato a tu código sería más cómodo leer para entender, por favor edita tu mensaje original y encierralo en etiquetas de highlight.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 31/08/2015, 20:06
 
Fecha de Ingreso: junio-2015
Mensajes: 5
Antigüedad: 8 años, 9 meses
Puntos: 0
Respuesta: No graba registros en base de datos

Estimado Pateketrueke:

Muchas gracias por responder e interesarte en buscar una solución, lamentablemente soy nuevo en el foro y no supe como encerrar el mensaje original en etiquetas highlight

pero segui intentando buscar soluciones, al final lo que hice fue insertar un registro manualmente en PhpMyadmin y al hacerlo me mostro el codigo de insercion, copie este antes de mi sentencia

$sql= "INSERT INTO factura (etc..etc)

y comence a remplazar los valores por mis valores obtenidos por $_POST.. y me grabo...

lo que cambio del codigo fue lo siguiente:

CODIGO ORIGINAL

$sql = "INSERT INTO `factura`
('concepto', 'cliente', 'fecha', 'rnc', 'ncf', 'subtotal', 'impuestos', 'total', 'ci')
VALUES
({$this->concepto}',
'{$this->cliente}',
'{$this->fecha}',
'{$this->rnc}',
'{$this->ncf}',
'{$this->subtotal}',
'{$this->impuestos}',
'{$this->total}',
'{$this->ci}');";


POR ESTE CÓDIGO QUE ME DIO LA INSERCIÓN DEL PRIMER REGISTRO EN FORMA MANUAL:

$sql= "INSERT INTO `facil`.`factura` (`concepto`, `fecha`, `cliente`, `rnc`, `ncf`, `subtotal`, `impuesto`, `total`, `ci`) VALUES ('{$this->concepto}', '{$this->fecha}', '{$this->cliente}', '{$this->rnc}', '{$this->ncf}', '{$this->subtotal}', '{$this->impuestos}', '{$this->total}', '{$this->ci}')";


El resto estaba todo bien, y al hacer este cambio todo resulto de manera correcta y ahora graba los registros en la tabla factura..

Altamente agradecido de tu persona

Rtel

Etiquetas: fecha, graba, html, mysql, registro, registros, 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 02:53.