Sunteți pe pagina 1din 13

MANTENIMENTO DE BASE DE DATOS CON DAO

Data Access Object, un componente


de software que facilita el acceso a
datos almacenados.

BEAN
Es una clase destinada a almacenar
una cantidad de datos para nuestro
programa. Su fin es encapsular
información, para reutilizar código
fuente, estructurando el código
fuente en unidades lo más sencillas
posible

El Controlador.

Esta parte del patrón es la


que define la lógica de
administración del sistema,
establece la conexión entre la
vista y el modelo.

UTIL

Conexión a la Base de Datos


222222222222222222222222222

<?php
class ConexionBD{
const SERVER = "localhost";
const USER = "root";
const PASS = "";
const DATABASE = "bd_basico";
private $cn = null;
public function getConexionBD()
{
try
{
//me pase a mysqli :v
$this->cn = mysqli_connect(self::SERVER, self::USER, self::PASS, self::DATABASE);
$this->cn->set_charset("utf8");
}
catch(Exception $e)
{ }
return $this->cn;
}
}
?>
<?php
class ProductoBean {
public $idProducto;
public $numero;
public $tipo;
public $precio;
function getIdProducto() {
return $this->idProducto;
}
function getNumero() {
return $this->numero;
}
function getTipo() {
return $this->tipo;
}
function getPrecio() {

return $this->precio;

function setIdProducto($idProducto) {
$this->idProducto = $idProducto;
}
function setNumero($numero) {

$this->numero = $numero;

function setTipo($tipo) {

$this->tipo = $tipo;

function setPrecio($precio) {

$this->precio = $precio;

?>
<?php
require_once '../BEAN/ProductoBean.php';
require_once '../UTIL/ConexionBD.php';
class ProductoDao {
public function ListarProductos()
{
try {
$cn = new ConexionBD();
$cnx = $cn->getConexionBD();
$sql = " SELECT idProducto as id, numero as numero, tipo as tipo, precio as precio FROM `tbl_producto` ";
$result = mysqli_query($cnx, $sql);
$Lista['data'] = array();
while($row = mysqli_fetch_assoc($result))
{
array_push($Lista['data'],
array('id'=>$row['id'],'numero'=>$row['numero'],'tipo'=>$row['tipo'],'precio'=>$row['precio']));
}
} catch (Exception $exc) {
echo mysqli_error($cnx);
echo $exc->getTraceAsString();
}
return $Lista;
}
public function RegistrarProducto(ProductoBean $objprobean)
{
try {
$cn = new ConexionBD();
$cnx = $cn->getConexionBD();
$sql = " INSERT INTO `tbl_producto` (`idProducto`, `numero`, `tipo`, `precio`) VALUES (NULL, '$objprobean-
>numero', '$objprobean->tipo', '$objprobean->precio'); ";
$estado = 0;
$result = mysqli_query($cnx, $sql);
if($result)
{
$estado = 1;
}else
{
$estado = 2;
echo mysqli_error($cnx);
}
} catch (Exception $exc) {

$estado = 0;

echo mysqli_error($cnx);

echo $exc->getTraceAsString();

return $estado;

public function ModificarProducto(ProductoBean $objprobean)


{
try { $cn = new ConexionBD();
$cnx = $cn->getConexionBD();
$sql = " UPDATE `tbl_producto` SET `numero` = '$objprobean->numero', `tipo` = '$objprobean->tipo',
`precio` = '$objprobean->precio' WHERE `tbl_producto`.`idProducto` = $objprobean->idProducto; ";
$estado = 0;
$result = mysqli_query($cnx, $sql);
if(mysqli_affected_rows($cnx))

{ $estado = 1;

}else

{ $estado = 2;

echo mysqli_error($cnx);

} catch (Exception $exc) {

$estado = 0;

echo mysqli_error($cnx);

echo $exc->getTraceAsString();

return $estado;

}
public function EliminarProducto(ProductoBean $objprobean)

try {

$cn = new ConexionBD();

$cnx = $cn->getConexionBD();

$sql = " DELETE FROM `tbl_producto` WHERE `tbl_producto`.`idProducto` = $objprobean->idProducto ";

$estado = 0;

$result = mysqli_query($cnx, $sql);

if(mysqli_affected_rows($cnx))

$estado = 1;

}else

$estado = 2;

echo mysqli_error($cnx);

} catch (Exception $exc) {

$estado = 0;

echo mysqli_error($cnx);

echo $exc->getTraceAsString();

return $estado;

}
public function BuscarProducto(ProductoBean $objprobean)
{

try {

$cn = new ConexionBD();

$cnx = $cn->getConexionBD();

$sql = "SELECT idProducto as id, numero as numero, tipo as tipo, precio as precio FROM `tbl_producto`
WHERE numero = '$objprobean->numero' ";

$Lista = array();

$result = mysqli_query($cnx, $sql);

$row = mysqli_fetch_assoc($result);

$Lista[] = array('id'=>$row['id'],'numero'=>$row['numero'],'tipo'=>$row['tipo'],'precio'=>$row['precio']);

} catch (Exception $exc) {

echo $exc->getTraceAsString();

echo mysqli_error($cnx);

return $Lista;

?>
<?php
require_once '../BEAN/ProductoBean.php';
require_once '../DAO/ProductoDao.php';
$op = htmlentities($_POST['op']);
switch ($op)
{
case "Listar":{
$objprodao = new ProductoDao();
$Lista = $objprodao->ListarProductos();
echo json_encode($Lista,JSON_UNESCAPED_UNICODE);
break;}
case "Create":{
$objprodao = new ProductoDao();
$objprobean = new ProductoBean();
$numero = htmlentities($_POST['numero']);
$tipo = htmlentities($_POST['tipo']);
$precio = htmlentities($_POST['precio']);
$objprobean->setNumero($numero);
$objprobean->setTipo($tipo);
$objprobean->setPrecio($precio);
$estado = $objprodao->RegistrarProducto($objprobean);
echo ($estado===1) ? "success":"failed";
break;}
case "Update":{
$objprodao = new ProductoDao();
$objprobean = new ProductoBean();

$idProducto = htmlentities($_POST['idProducto']);
$numero = htmlentities($_POST['numeroUpdate']);
$tipo = htmlentities($_POST['tipoUpdate']);
$precio = htmlentities($_POST['precioUpdate']);

$objprobean->setIdProducto($idProducto);
$objprobean->setNumero($numero);
$objprobean->setTipo($tipo);
$objprobean->setPrecio($precio);
$estado = $objprodao->ModificarProducto($objprobean);
echo ($estado===1) ? "success":"failed";
break;}
case "Delete":{
$objprodao = new ProductoDao();
$objprobean = new ProductoBean();
$idProducto = htmlentities($_POST['id']);
$objprobean->setIdProducto($idProducto);
$estado = $objprodao->EliminarProducto($objprobean);
echo ($estado===1) ? "success":"failed";
break;}
case "Search":{
$objprodao = new ProductoDao();
$objprobean = new ProductoBean();
$numero = htmlentities($_POST['numero']);
$objprobean->setNumero($numero);
$Lista = $objprodao->BuscarProducto($objprobean);
echo json_encode($Lista,JSON_UNESCAPED_UNICODE);
break;}
default:
{break;}
}
?>
mantenimientojquery.js

$(document).ready(function(){

lista();

$('#buscarNumero').click(function(e){

e.preventDefault();

var numero = $('#numero').val();

$.ajax({

url:'./CONTROLADOR/ProductoControlador.php',

type:'POST',

contentType:'application/x-www-form-urlencoded; charset=UTF-8',

dataType: 'json',

data : {op:'Search',numero:numero},

success:function(response){

var tipo = response[0]['tipo'];

var precio = response[0]['precio'];

$("#tipo").val(tipo);

$("#precio").val(precio);

},fail: function(response)

{ console.log(typeof(response));

})

});

$('#clear').click(function(e){

e.preventDefault();

$('#formProductoRegister')[0].reset();

});
$('#register').click(function(e){

e.preventDefault();

var data = new FormData($('#formProductoRegister')[0]);

$.ajax({

url:'./CONTROLADOR/ProductoControlador.php',

type:'POST',

dataType: "text",

contentType: false,

processData: false,

data : data,

success:function(response){

//ESTA FUNCION indexOF es importante para comparar o buscar en la cadena un contenido

//retorna -1 si no lo encuentra , es muy util cuando hay callback de tipo string.

if(response.indexOf('success')> -1)

$('#dt_producto').DataTable().ajax.reload(null, false);

$('#formProductoRegister')[0].reset();

}else if(response.indexOf('error')> -1)

{ $('#dt_producto').DataTable().ajax.reload(null, false);

$('#formProductoRegister')[0].reset();

}else {

},fail: function(response)

{console.log(typeof(response));}

});

});

});

S-ar putea să vă placă și