Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1de 43

Seminario Regional I Programacin de bases de datos mediante el patrn de datos DAO Las aplicaciones que necesita para realizar

esta guia son: XAMPP, MySQL 5.0, MySQLworkbench, MysqlFront Descarguelos de estos sitios: http://www.apachefriends.org/en/xampp-windows.html http://dev.mysql.com/downloads/ http://mysql-front.softonic.com/descargar Antes de elaborar la prctica, por favor lea este documento en la siguiente URL http://www.proactiva-calidad.com/java/patrones/DAO.html http://www.genbetadev.com/java-j2ee/spring-framework-el-patrn-dao http://eisc.univalle.edu.co/materias/Material_Desarrollo_Software/expoDAO.pdf

Objetivos: Desarrollar una aplicacin web Cliente Servidor, en un Servidor Apache con PHP, MySql y patrn de datos DAO. Disear los mtodos que permitan interactuar con la base de datos tales como adicionar, buscar, eliminar, modificar y listar.

Arquitectura Cliente Servidor

Cliente

Cliente AJAX Protocolo HTTP

Servidor de

Lgica de Negocio

ClienteValueObje

AJAX Acceso a Datos

Cliente.php

SQL

Para el desarrollo de aplicaciones Web en PHP, MySQL, y Apache y modelo de datos DAO, se requieren de los siguientes Software:

descarga procedemos a su respectiva instalacion

Clic en siguiente

Escogemos la opcin Typical, clic en Next

Clic en Install

Seleccione la opcin Skip Sign-Up, por el momento no queremos crear nuevas cuentas, sino que utilizaremos la que el crea por defecto. Clic en Next

Cheque Configure the MySql Server now, con el objeto de configurar el servidor de bases de datos. Clic en Finis

A continuacin procederemos a configurar el servidor

Clic en Next

Escogemos la opcin Detailed Configuration Clic en Next

Como podemos ver hay tres opciones para configurar el servidor de BD, la primera es: Developer Machine, esta opcin nos permite configurar el servidor para que se desarrollen aplicaciones dentro de l, el consumo de memoria es mnimo. Server Machina. Se configura de tal manera que se puedan correr mltiples aplicaciones dentro de l. Como por ejemplo acceso desde la web. Dedicated MySql Server Machihe. Se configura como maquina dedicada para correr solamente MySql. El consumo de memoria es la disponibilidad que se tenga.

Para efectos del desarrollo de nuestra aplicacin escogeremos la primera opcin Developer Machine . Clic en Next

Aqu configuraremos la instancia del servidor, para ello contamos con tres opciones: Multifuncional Database. Es una base de datos de proposito general. Este servidor estara para ser usado en transacciones rpidas con InnoDB y MsISAM. Transactional Database Only. Configurado para transacciones de aplicaciones web. Non- Transactional Database Only: Es una suite para simples aplicaciones, monitoreo y logueo de aplicaciones como son los anlisis de programa.

Para efectos de nuestro proyecto seleccionamos la opcin Multifuncional Database. Clic en Next

Escogemos el directorio donde se encuentra alojada nuestra base de datos. Por defecto dejamos tal y como esta en la figura. Clic en Next

A continuacin determinaremos las concurrencias a nuestro servidor de BD. Seleccionamos la opcin Decisin Support (DSS)-OLAP. Clic en Next

Escogemos el puerto para nuestro servidor de BD, en este caso seleccionamos el puerto por defecto que es el 3306. Clic en Next

Escogemos el tipo de caracteres que puede reconocer nuestro servidor de DB, en este caso escogemos la opcin Manual Selected Default Carcter set-Collation y el carcter set: utf8. Clic en Next.

Aqu escogemos la forma en que se cargue el servicio manual o automtica, esto ya queda a criterios del desarrollador, seleccionamos la opcin Install As Windows Service, y seleccionamos el servicio MySql y lo habilitamos como un servicio automtico. Clic en Next

No checamos ninguna de las opciones, para dejar por defecto la que trae el servidor que es: username : root Password : Clic en Next

Clic en Execute

Clic en Finish

Y ya hemos configurado nuestro servidor de Bases de Datos MySql.

Ahora lo que necesitamos es instalar nuestros accesorios tales como: MySqlFront Nos permite visualizar el contenido de nuestro servidor

Si iniciamos por primera vez tenemos que crear una nueva conexin, el Hostname es: localhost, user: root password:

Hacemos clic en connect

Desde este despliegue podemos interactuar con el servidor de BD.

A continuacin procedemos a desarrollar la aplicacin:

Entre a su navegador y escriba la siguiente direccin Web http://www.titaniclinux.net/daogen

Para el mapeo a DAO contamos con lo siguiente: Database Table Name: Escribimos el Nombre de nuestra tabla

Class Name (defaults to table name): Escribimos si queremos el mismo nombre de la tabla Target Language: Seleccionamos PHP Database Server: Seleccionamos MySql Dao-level object cache: Si necesitamos datos en cache podemos usar habilitar la opcin Total number of Columns: Se refiere al numero de atributos del objeto PrimaryKey (PK) Columns : Es obligatorio asignarle una llave primaria Runtime variables: se deja en 0

Clic en continue to Details

Este es opcional no lo use solo analcelo

Save this code in a file named "Clientes.xml" (optional)


<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> <!DOCTYPE daogen-metadata> <daogen-metadata> <version>2.4.1</version> <timestamp>30.09.2011</timestamp> <tableName>Clientes</tableName> <className>Clientes</className> <language>php</language> <database>mysql</database> <useCache>false</useCache> <classPackage></classPackage> <columns> <dbColumn PK="true" colType="String" colName="IdClientes" varName="IdClientes" automatic="false" valueSource="" indexed="true" colLength="255" orderLevel="1" orderType="ASC" /> <dbColumn PK="false" colType="String" colName="Nombres" varName="Nombres" automatic="false" valueSource="" indexed="false" colLength="255" orderLevel="0" orderType="ASC" /> <dbColumn PK="false" colType="String" colName="Apellidos" varName="Apellidos" automatic="false" valueSource="" indexed="false" colLength="255" orderLevel="0" orderType="ASC" />

</columns> </daogen-metadata>

Save this code in a file named "Clientes.sql" (optional)


# SQL command to create the table: # Remember to correct VARCHAR column lengths to proper values # and add additional indexes for your own extensions. # # # # # If you had prepaired CREATE TABLE SQL-statement before, make sure that this automatically generated code is compatible with your own code. If SQL code is incompatible, it is not possible to use these generated sources successfully. (Changing VARCHAR column lenghts will not break code.)

CREATE TABLE Clientes ( IdClientes varchar(255) NOT NULL, Nombres varchar(255), Apellidos varchar(255), PRIMARY KEY(IdClientes), INDEX Clientes_IdClientes_INDEX (IdClientes));

A continuacin abra netbeans y siga las siguientes instrucciones. Elabore un nuevo proyecto PHP

Clic en siguiente

Llamelo Myproyecto y gurdelo dentro de la carpeta contenedora de los httpdocs de Xampp Y haga clic en finis A continuacin elabore un folder llamado banco

A continuacin elabore una clase llamada Clientes.php y reemplace el cdigo por este

Save this code in a file named "Clientes.php"


<?php

/** * Clientes Value Object. * This class is value object representing database table Clientes * This class is intented to be used together with associated Dao object. */ /** * This sourcecode has been generated by FREE DaoGen generator version 2.4.1. * The usage of generated code is restricted to OpenSource software projects * only. DaoGen is available in http://titaniclinux.net/daogen/ * It has been programmed by Tuomo Lukka, [email protected] * * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full text for license is available * in GNU project's pages: http://www.gnu.org/copyleft/gpl.html * * If you wish to use the DaoGen generator to produce code for closed-source * commercial applications, you must pay the lisence fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations with all supported languages

* for each database table you are paying for.) Send mail to * "[email protected]" for more information. Thank you! */

class Clientes { /** * Persistent Instance variables. This data is directly * mapped to the columns of database table. */ var $IdClientes; var $Nombres; var $Apellidos;

/** * Constructors. DaoGen generates two constructors by default. * The first one takes no arguments and provides the most simple * way to create object instance. The another one takes one * argument, which is the primary key of the corresponding table. */ function Clientes () { } /* function Clientes ($IdClientesIn) { $this->IdClientes = $IdClientesIn; } */

/** * Get- and Set-methods for persistent variables. The default * behaviour does not make any checks against malformed data, * so these might require some manual additions. */ function getIdClientes() { return $this->IdClientes; } function setIdClientes($IdClientesIn) { $this->IdClientes = $IdClientesIn; } function getNombres() { return $this->Nombres; } function setNombres($NombresIn) { $this->Nombres = $NombresIn; }

function getApellidos() { return $this->Apellidos; } function setApellidos($ApellidosIn) { $this->Apellidos = $ApellidosIn; }

/** * setAll allows to set all * This is useful, when all * set the initial state of * directly modify instance * individual set-methods. */

persistent variables in one method call. data is available and it is needed to this object. Note that this method will variales, without going trough the

function setAll($IdClientesIn, $NombresIn, $ApellidosIn) { $this->IdClientes = $IdClientesIn; $this->Nombres = $NombresIn; $this->Apellidos = $ApellidosIn; }

/** * hasEqualMapping-method will compare two Clientes instances * and return true if they contain same values in all persistent instance * variables. If hasEqualMapping returns true, it does not mean the objects * are the same instance. However it does mean that in that moment, they * are mapped to the same row in database. */ function hasEqualMapping($valueObject) { if ($valueObject->getIdClientes() != $this->IdClientes) { return(false); } if ($valueObject->getNombres() != $this->Nombres) { return(false); } if ($valueObject->getApellidos() != $this->Apellidos) { return(false); } return true; }

/** * toString will return String object representing the state of this * valueObject. This is useful during application development, and * possibly when application is writing object states in textlog. */ function toString() {

$out = $out = $out = $out = $out = $out = return }

$this->getDaogenVersion(); $out."\nclass Clientes, mapping to table Clientes\n"; $out."Persistent attributes: \n"; $out."IdClientes = ".$this->IdClientes."\n"; $out."Nombres = ".$this->Nombres."\n"; $out."Apellidos = ".$this->Apellidos."\n"; $out;

/** * Clone will return identical deep copy of this valueObject. * Note, that this method is different than the clone() which * is defined in java.lang.Object. Here, the retuned cloned object * will also have all its attributes cloned. */ function clone() { $cloned = new Clientes(); $cloned->setIdClientes($this->IdClientes); $cloned->setNombres($this->Nombres); $cloned->setApellidos($this->Apellidos); return $cloned; }

/** * getDaogenVersion will return information about * generator which created these sources. */ function getDaogenVersion() { return "DaoGen version 2.4.1"; } } ?>

A continuacin elabore una archive llamado "Datasource.php" y reemplcelo por este cdigo

<?php

/** * DaoGen MySQL Datasource-object.

* This class is an helper class to make sure the generated DaoGen * code does not depend on any specific Database-system. * * NOTE: You will need only one instance of this class to use multiple * DaoGen generated objects. This Datasource is a sample implementation * providing all needed methods for MySQL. However if you want to use * another Database-system, use this as a sample when you implement * Datasource for your preferred Database. */ /** * This sourcecode has been generated by FREE DaoGen generator version 2.4.1. * The usage of generated code is restricted to OpenSource software projects * only. DaoGen is available in http://titaniclinux.net/daogen/ * It has been programmed by Tuomo Lukka, [email protected] * * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full text for license is available * in GNU project's pages: http://www.gnu.org/copyleft/gpl.html * * If you wish to use the DaoGen generator to produce code for closed-source * commercial applications, you must pay the lisence fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations with all supported languages * for each database table you are paying for.) Send mail to * "[email protected]" for more information. Thank you! */

class Datasource { var $dbLink; /** * Constructor. Call this once when initializing system core. * Then save the instance of this class in $connection variable * and pass it as an argument when using services from core. */ function Datasource($dbHost, $dbName, $dbuser, $dbpasswd) { // Change this line to reflect whatever Database system you are using: $this->dbLink = mysql_connect ($dbHost, $dbuser, $dbpasswd); // Change this line to reflect whatever Database system you are using: mysql_select_db ($dbName, $this->dbLink); }

/** * Function to execute SQL-commands. Use this thin wrapper to avoid * MySQL dependency in application code.

*/ function execute($sql) { // Change this line to reflect whatever Database system you are using: $result = mysql_query($sql, $this->dbLink); $this->checkErrors($sql); return $result; }

/** * Function to "blindly" execute SQL-commands. This will not put up * any notifications if SQL fails, so make sure this is not used for * normal operations. */ function executeBlind($sql) { // Change this line to reflect whatever Database system you are using: $result = mysql_query($sql, $this->dbLink); return $result; }

/** * Function to iterate trough the resultset. Use this thin wrapper to * avoid MySQL dependency in application code. */ function nextRow ($result) { // Change this line to reflect whatever Database system you are using: $row = mysql_fetch_array($result); return $row; }

/** * Check if sql-queries triggered errors. This will be called after an * execute-command. Function requires attempted SQL string as parameter * since it can be logged to application spesific log if errors occurred. * This whole method depends heavily from selected Database-system. Make * sure you change this method when using some other than MySQL database. */ function checkErrors($sql) { //global $systemLog;

// Only thing that we need todo is define some variables // And ask from RDBMS, if there was some sort of errors. $err=mysql_error(); $errno=mysql_errno(); if($errno) { // SQL Error occurred. This is FATAL error. Error message and // SQL command will be logged and aplication will teminate immediately. $message = "The following SQL command ".$sql." caused Database error: ".$err."."; //$message = addslashes("SQL-command: ".$sql." errormessage: ".$message); //$systemLog->writeSystemSqlError ("SQL Error occurred", $errno, $message); print "Unrecowerable error has occurred. All data will be logged."; print "Please contact System Administrator for help! \n"; print "<!-- ".$message." -->\n"; exit; } else { // Since there was no error, we can safely return to main program. return; } } } ?>

A continuacin elabore un archive llamado "ClientesDao.php" y reemplace el cdigo por este:


<?php

/** * Clientes Data Access Object (DAO). * This class contains all database handling that is needed to * permanently store and retrieve Clientes object instances. */ /** * This sourcecode has been generated by FREE DaoGen generator version 2.4.1. * The usage of generated code is restricted to OpenSource software projects * only. DaoGen is available in http://titaniclinux.net/daogen/ * It has been programmed by Tuomo Lukka, [email protected]

* * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full text for license is available * in GNU project's pages: http://www.gnu.org/copyleft/gpl.html * * If you wish to use the DaoGen generator to produce code for closed-source * commercial applications, you must pay the lisence fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations with all supported languages * for each database table you are paying for.) Send mail to * "[email protected]" for more information. Thank you! */

class ClientesDao {

/** * createValueObject-method. This method is used when the Dao class needs * to create new value object instance. The reason why this method exists * is that sometimes the programmer may want to extend also the valueObject * and then this method can be overrided to return extended valueObject. * NOTE: If you extend the valueObject class, make sure to override the * clone() method in it! */ function createValueObject() { return new Clientes(); }

/** * getObject-method. This will create and load valueObject contents from database * using given Primary-Key as identifier. This method is just a convenience method * for the real load-method which accepts the valueObject as a parameter. Returned * valueObject will be created using the createValueObject() method. */ function getObject(&$conn, $IdClientes) { $valueObject = $this->createValueObject(); $valueObject->setIdClientes($IdClientes); $this->load(&$conn, &$valueObject); return $valueObject; }

/** * load-method. This will load valueObject contents from database using * Primary-Key as identifier. Upper layer should use this so that valueObject * instance is created and only primary-key should be specified. Then

call * this method to complete other persistent information. This method will * overwrite all other fields except primary-key and possible runtime variables. * If load can not find matching row, NotFoundException will be thrown. * * @param conn This method requires working database connection. * @param valueObject This parameter contains the class instance to be loaded. * Primary-key field must be set for this to work properly. */ function load(&$conn, &$valueObject) { if (!$valueObject->getIdClientes()) { //print "Can not select without Primary-Key!"; return false; } $sql = "SELECT * FROM Clientes WHERE (IdClientes = '".$valueObject>getIdClientes()."') "; if ($this->singleQuery(&$conn, $sql, &$valueObject)) return true; else return false; }

/** * LoadAll-method. This will read all contents from database table and * build an Vector containing valueObjects. Please note, that this method * will consume huge amounts of resources if table has lot's of rows. * This should only be used when target tables have only small amounts * of data. * * @param conn This method requires working database connection. */ function loadAll(&$conn) {

$sql = "SELECT * FROM Clientes ORDER BY IdClientes ASC "; $searchResults = $this->listQuery(&$conn, $sql); return $searchResults; }

/** * create-method. This will create new row in database according to supplied * valueObject contents. Make sure that values for all NOT NULL columns are * correctly specified. Also, if this table does not use automatic surrogate-keys

* the primary-key must be specified. After INSERT command this method will * read the generated primary-key back to valueObject if automatic surrogate-keys * were used. * * @param conn This method requires working database connection. * @param valueObject This parameter contains the class instance to be created. * If automatic surrogate-keys are not used the Primary-key * field must be set for this to work properly. */ function create(&$conn, &$valueObject) { $sql = "INSERT INTO Clientes ( IdClientes, Nombres, Apellidos) VALUES ('".$valueObject->getIdClientes()."', "; $sql = $sql."'".$valueObject->getNombres()."', "; $sql = $sql."'".$valueObject->getApellidos()."') "; $result = $this->databaseUpdate(&$conn, $sql);

return true; }

/** * save-method. This method will save the current state of valueObject to database. * Save can not be used to create new instances in database, so upper layer must * make sure that the primary-key is correctly specified. Primary-key will indicate * which instance is going to be updated in database. If save can not find matching * row, NotFoundException will be thrown. * * @param conn This method requires working database connection. * @param valueObject This parameter contains the class instance to be saved. * Primary-key field must be set for this to work properly. */ function save(&$conn, &$valueObject) { $sql = "UPDATE Clientes SET Nombres = '".$valueObject>getNombres()."', "; $sql = $sql."Apellidos = '".$valueObject->getApellidos()."'"; $sql = $sql." WHERE (IdClientes = '".$valueObject>getIdClientes()."') "; $result = $this->databaseUpdate(&$conn, $sql); if ($result != 1) { //print "PrimaryKey Error when updating DB!"; return false; }

return true; }

/** * delete-method. This method will remove the information from database as identified by * by primary-key in supplied valueObject. Once valueObject has been deleted it can not * be restored by calling save. Restoring can only be done using create method but if * database is using automatic surrogate-keys, the resulting object will have different * primary-key than what it was in the deleted object. If delete can not find matching row, * NotFoundException will be thrown. * * @param conn This method requires working database connection. * @param valueObject This parameter contains the class instance to be deleted. * Primary-key field must be set for this to work properly. */ function delete(&$conn, &$valueObject) {

if (!$valueObject->getIdClientes()) { //print "Can not delete without Primary-Key!"; return false; } $sql = "DELETE FROM Clientes WHERE (IdClientes = '".$valueObject>getIdClientes()."') "; $result = $this->databaseUpdate(&$conn, $sql); if ($result != 1) { //print "PrimaryKey Error when updating DB!"; return false; } return true; }

/** * deleteAll-method. This method will remove all information from the table that matches * this Dao and ValueObject couple. This should be the most efficient way to clear table. * Once deleteAll has been called, no valueObject that has been created before can be * restored by calling save. Restoring can only be done using create method but if database * is using automatic surrogate-keys, the resulting object will have different primary-key * than what it was in the deleted object. (Note, the implementation of this method should * be different with different DB backends.)

* * @param conn This method requires working database connection. */ function deleteAll(&$conn) { $sql = "DELETE FROM Clientes"; $result = $this->databaseUpdate(&$conn, $sql); return true; }

/** * coutAll-method. This method will return the number of all rows from table that matches * this Dao. The implementation will simply execute "select count(primarykey) from table". * If table is empty, the return value is 0. This method should be used before calling * loadAll, to make sure table has not too many rows. * * @param conn This method requires working database connection. */ function countAll(&$conn) { $sql = "SELECT count(*) FROM Clientes"; $allRows = 0; $result = $conn->execute($sql); if ($row = $conn->nextRow($result)) $allRows = $row[0]; return $allRows; }

/** * searchMatching-Method. This method provides searching capability to * get matching valueObjects from database. It works by searching all * objects that match permanent instance variables of given object. * Upper layer should use this by setting some parameters in valueObject * and then call searchMatching. The result will be 0-N objects in vector, * all matching those criteria you specified. Those instance-variables that * have NULL values are excluded in search-criteria. * * @param conn This method requires working database connection. * @param valueObject This parameter contains the class instance where search will be based. * Primary-key field should not be set. */ function searchMatching(&$conn, &$valueObject) { $first = true; $sql = "SELECT * FROM Clientes WHERE 1=1 ";

if ($valueObject->getIdClientes() != "") { if ($first) { $first = false; } $sql = $sql."AND IdClientes LIKE '".$valueObject>getIdClientes()."%' "; } if ($valueObject->getNombres() != "") { if ($first) { $first = false; } $sql = $sql."AND Nombres LIKE '".$valueObject->getNombres()."%' "; } if ($valueObject->getApellidos() != "") { if ($first) { $first = false; } $sql = $sql."AND Apellidos LIKE '".$valueObject>getApellidos()."%' "; }

$sql = $sql."ORDER BY IdClientes ASC "; // Prevent accidential full table results. // Use loadAll if all rows must be returned. if ($first) return array(); $searchResults = $this->listQuery(&$conn, $sql); return $searchResults; }

/** * getDaogenVersion will return information about * generator which created these sources. */ function getDaogenVersion() { return "DaoGen version 2.4.1"; }

/** * databaseUpdate-method. This method is a helper method for internal use. It will execute * all database handling that will change the information in tables. SELECT queries will * not be executed here however. The return value indicates how many rows were affected. * This method will also make sure that if cache is used, it will reset when data changes. * * @param conn This method requires working database connection. * @param stmt This parameter contains the SQL statement to be excuted. */ function databaseUpdate(&$conn, &$sql) {

$result = $conn->execute($sql); return $result; }

/** * databaseQuery-method. This method is a helper method for internal use. It will execute * all database queries that will return only one row. The resultset will be converted * to valueObject. If no rows were found, NotFoundException will be thrown. * * @param conn This method requires working database connection. * @param stmt This parameter contains the SQL statement to be excuted. * @param valueObject Class-instance where resulting data will be stored. */ function singleQuery(&$conn, &$sql, &$valueObject) { $result = $conn->execute($sql); if ($row = $conn->nextRow($result)) { $valueObject->setIdClientes($row[0]); $valueObject->setNombres($row[1]); $valueObject->setApellidos($row[2]); } else { //print " Object Not Found!"; return false; } return true; }

/** * databaseQuery-method. This method is a helper method for internal use. It will execute * all database queries that will return multiple rows. The resultset will be converted * to the List of valueObjects. If no rows were found, an empty List will be returned. * * @param conn This method requires working database connection. * @param stmt This parameter contains the SQL statement to be excuted. */ function listQuery(&$conn, &$sql) { $searchResults = array(); $result = $conn->execute($sql); while ($row = $conn->nextRow($result)) {

$temp = $this->createValueObject(); $temp->setIdClientes($row[0]); $temp->setNombres($row[1]); $temp->setApellidos($row[2]); array_push($searchResults, $temp); } return $searchResults; } } ?>

Y finalmente elabore un archivo llamado imp_clientes.php y reemplcelo por este cdigo: <?php require("Datasource.php");// Esta es la clase de la fuente de datos require("Clientes.php");// Esta es la clase que contiene los mtodos del objeto require("ClientesDao.php"); //Esta es la clase que hace el llamado a las clase Cli.php y CliDao.php. $connection = new Datasource("localhost", "banco", "root", "");// Instanciamos la conexion $CliHandler = new ClientesDao();// Instanciamos a la clase CliDao, para accesar a sus metodos $Cli =new Clientes();

if ($HTTP_POST_VARS['action'] == 'buscar') { $Cli=$CliHandler->getObject($connection,$_POST['codigo']); if ($Cli->getnombres()!="") { $codigo=$Cli->getIdClientes(); $nombre=$Cli->getNombres(); $apellidos=$Cli->getApellidos(); } else { $codigo=""; ?> <script>alert("!, Este Cliente no existe!");</script> <?php } }

if ($HTTP_POST_VARS['action'] == 'modificar') { $Cli=$CliHandler->getObject($connection,$_POST['codigo']); if ($Cli->getnombres()!="") { $Cli->setNombres($_POST['nombres']); $Cli->setApellidos($_POST['apellidos']); $CliHandler->save($connection,$Cli); $codigo=""; $nombre=""; $apellidos=""; $direccion=""; $telefono=""; ?> <script>alert("Registro Modificado satisfactoriamente!");</script> <?php } else { $codigo=""; ?> <script>alert("!, Este estudiante no existe!");</script> <?php } } if ($HTTP_POST_VARS['action'] == 'eliminar') { $Cli=$CliHandler->getObject($connection,$_POST['codigo']); if ($Cli->getnombres()!="") { $Cli->setIdClientes($_POST['codigo']); $Cli->setNombres($_POST['nombres']); $Cli->setApellidos($_POST['apellidos']); $CliHandler->delete($connection,$Cli); $codigo=""; $nombre=""; $apellidos=""; ?> <script>alert("Registro eliminado satisfactoriamente!");</script> <?php

else { $codigo=""; ?> <script>alert("!, Este estudiante no existe!");</script> <?php } } if ($HTTP_POST_VARS['action'] == 'guardar') { //$Cli=$CliHandler->getObject($connection,$_POST['codigo']); $Cli=$CliHandler->getObject($connection,$_POST['codigo']); if ($Cli->getNombres()=="") { $Cli->setIdClientes($_POST['codigo']); $Cli->setnombres($_POST['nombres']); $Cli->setApellidos($_POST['apellidos']); $CliHandler->create($connection,$Cli); $codigo=""; $nombre=""; $apellidos=""; ?> <script>alert("Registro adicionado satisfactoriamente!");</script> <?php } else { ?>

<script>alert("!, Ya existe un registro con este codigo!");</script> <?php } } ///Listar if ($HTTP_POST_VARS['action'] == 'listar') {

echo "<table border = '2'> \n"; echo "<tr> \n";

echo "<td><b>Indentificacion</b></td> \n"; echo "<td><b>Nombres</b></td> \n"; echo "<td><b>Apellidos</b></td> \n"; echo "</tr> \n"; $vector=$CliHandler->loadAll($connection); foreach($vector as $indice => $valor) { $Objeto= $valor; echo "<td>".$Objeto->getIdClientes()."</td>\n"; echo "<td>".$Objeto->getNombres()."</td>\n"; echo "<td>".$Objeto->getApellidos()."</td>\n"; echo "</tr> \n"; } echo "</table> \n"; } if ($HTTP_POST_VARS['action'] == 'cancelar') { //$Cli=$CliHandler->getObject($connection,$_POST['codigo']); $codigo=""; $nombre=""; $apellidos="";

} ?>

<html> <head> <title>Modulo de Clientes</title> </head> <BODY text=#ccffff vLink=#99cccc aLink=#66ff99 link=#ffcc99 bgColor=#6699cc background=""> <h1>Modulo de Clientes</h1>

<form method="post" action="<?php echo $PHP_SELF?>"> <?php

?> <table border=10> <tr><td>Codigo:</td><td><input type="Text" name="codigo" value="<?php echo $codigo

?>"></td></tr> <tr><td>Nombres:</td><td><input type="Text" name="nombres" value="<?php echo $nombre ?>"></td></tr> <tr><td>Apellidos:</td><td><input type="Text" name="apellidos" value="<?php echo $apellidos?>"></td></tr> </table> <table border=10> <tr><td><input type="submit" name="action" value="buscar"></td> <td><input type="submit" name="action" value="guardar" onClick="return Enviar(this.form)"></td></tr> <tr><td><input type="submit" name="action" value="modificar" onClick="return Enviar(this.form)"></td> <td><input type="submit" name="action" value="eliminar" onClick="return Enviar(this.form)"></td></tr> <tr><td><input type="submit" name="action" value="cancelar" onclick="Limpiar(this.form)"></td> <tr><td><input type="submit" name="action" value="listar" onclick="Enviar(this.form)"></td> <td><input type="submit" name="action" value="cerrar" onclick="window.close()"></td></tr> </form> </body> </html>

Al final tendra una aplicacin como esta

Actividad: elabore el mtodo modificar y eliminar

También podría gustarte