Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

43
Seminario Regional I Programación de bases de datos mediante el patrón 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 práctica, 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 aplicación web Cliente – Servidor, en un Servidor Apache con PHP, MySql y patrón de datos DAO. - Diseñar los métodos que permitan interactuar con la base de datos tales como adicionar, buscar, eliminar, modificar y listar. Arquitectura Cliente Servidor SQL Protocolo HTTP Cliente Lógica de Negocio Acceso a Datos ClienteValueObje Cliente.php Servidor de AJAX Cliente AJAX

Transcript of Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Page 1: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Seminario Regional I

Programación de bases de datos mediante el patrón 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 práctica, 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 aplicación web Cliente – Servidor, en un Servidor Apache con PHP, MySql y

patrón de datos DAO.

- Diseñar los métodos que permitan interactuar con la base de datos tales como adicionar,

buscar, eliminar, modificar y listar.

Arquitectura Cliente Servidor

SQL

Protocolo HTTP

Cliente

Lógica de Negocio

Acceso a Datos

ClienteValueObje

Cliente.php

Servidor de

AJAX

Cliente AJAX

Page 2: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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

Page 3: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Clic en siguiente

Escogemos la opción Typical, clic en Next

Page 4: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Clic en Install

Page 5: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Seleccione la opción 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 continuación procederemos a configurar el servidor

Page 6: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Clic en Next

Page 7: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Escogemos la opción Detailed Configuration

Clic en Next

Page 8: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Como podemos ver hay tres opciones para configurar el servidor de BD, la primera es:

- Developer Machine, esta opción nos permite configurar el servidor para que se desarrollen

aplicaciones dentro de él, el consumo de memoria es mínimo.

- Server Machina. Se configura de tal manera que se puedan correr múltiples 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 aplicación escogeremos la primera opción Developer Machine .

Clic en Next

Page 9: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Aquí configuraremos la instancia del servidor, para ello contamos con tres opciones:

- Multifuncional Database. Es una base de datos de proposito general. Este servidor estaría para ser

usado en transacciones rápidas 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 análisis de programa.

Para efectos de nuestro proyecto seleccionamos la opción Multifuncional Database. Clic en Next

Page 10: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Escogemos el directorio donde se encuentra alojada nuestra base de datos. Por defecto dejamos tal y

como esta en la figura. Clic en Next

Page 11: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

A continuación determinaremos las concurrencias a nuestro servidor de BD.

Seleccionamos la opción Decisión Support (DSS)-OLAP.

Clic en Next

Page 12: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Escogemos el puerto para nuestro servidor de BD, en este caso seleccionamos el puerto por defecto que

es el 3306. Clic en Next

Page 13: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Escogemos el tipo de caracteres que puede reconocer nuestro servidor de DB, en este caso escogemos

la opción Manual Selected Default Carácter set-Collation y el carácter set: utf8.

Clic en Next.

Page 14: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Aquí escogemos la forma en que se cargue el servicio manual o automática, esto ya queda a criterios del

desarrollador, seleccionamos la opción Install As Windows Service, y seleccionamos el servicio MySql y

lo habilitamos como un servicio automático. Clic en Next

Page 15: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

No checamos ninguna de las opciones, para dejar por defecto la que trae el servidor que es: username :

root

Password :

Clic en Next

Page 16: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Clic en Execute

Page 17: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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 conexión, el Hostname es: localhost,

user: root

password:” ”

Hacemos clic en connect

Page 18: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Desde este despliegue podemos interactuar con el servidor de BD.

A continuación procedemos a desarrollar la aplicación:

Entre a su navegador y escriba la siguiente dirección Web

http://www.titaniclinux.net/daogen

Page 19: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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 opción

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

Page 20: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Este es opcional no lo use solo analícelo

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

<?xml version="1.0" encoding="ISO-8859-1" standalon e="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="tru e" colLength="255" orderLevel="1" orderType="ASC" /> <dbColumn PK="false" colType="String" colName ="Nombres" varName="Nombres" automatic="false" valueSource="" indexed="fal se" colLength="255" orderLevel="0" orderType="ASC" /> <dbColumn PK="false" colType="String" colName ="Apellidos" varName="Apellidos" automatic="false" valueSource="" indexed="fal se" colLength="255" orderLevel="0" orderType="ASC" />

Page 21: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

</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 pro per values # and add additional indexes for your own extension s. # If you had prepaired CREATE TABLE SQL-statement b efore, # make sure that this automatically generated code is # compatible with your own code. If SQL code is inc ompatible, # it is not possible to use these generated sources successfully. # (Changing VARCHAR column lenghts will not break c ode.) CREATE TABLE Clientes ( IdClientes varchar(255) NOT NULL, Nombres varchar(255), Apellidos varchar(255), PRIMARY KEY(IdClientes), INDEX Clientes_IdClientes_INDEX (IdClientes));

A continuación abra netbeans y siga las siguientes instrucciones. Elabore un nuevo proyecto PHP

Page 22: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Clic en siguiente

Page 23: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Llamelo Myproyecto y guárdelo dentro de la carpeta contenedora de los httpdocs de Xampp

Y haga clic en finis

A continuación elabore un folder llamado banco

Page 24: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

A continuación elabore una clase llamada Clientes.php y reemplace el código por este

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

<?php /** * Clientes Value Object. * This class is value object representing databas e table Clientes * This class is intented to be used together with associated Dao object. */ /** * This sourcecode has been generated by FREE DaoG en generator version 2.4.1. * The usage of generated code is restricted to Op enSource software projects * only. DaoGen is available in http://titaniclinu x.net/daogen/ * It has been programmed by Tuomo Lukka, Tuomo.Lu [email protected] * * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full te xt for license is available * in GNU project's pages: http://www.gnu.org/copy left/gpl.html * * If you wish to use the DaoGen generator to prod uce code for closed-source * commercial applications, you must pay the lisen ce fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations w ith all supported languages

Page 25: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

* for each database table you are paying for.) Se nd mail to * "[email protected]" for more information. Than k 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 construct ors by default. * The first one takes no arguments and provide s the most simple * way to create object instance. The another o ne takes one * argument, which is the primary key of the co rresponding table. */ function Clientes () { } /* function Clientes ($IdClientesIn) { $this->IdClientes = $IdClientesIn; } */ /** * Get- and Set-methods for persistent variable s. The default * behaviour does not make any checks against m alformed 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; }

Page 26: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

function getApellidos() { return $this->Apellidos; } function setApellidos($ApellidosIn) { $this->Apellidos = $ApellidosIn; } /** * setAll allows to set all persistent variable s in one method call. * This is useful, when all data is available a nd it is needed to * set the initial state of this object. Note t hat this method will * directly modify instance variales, without g oing trough the * individual set-methods. */ function setAll($IdClientesIn, $NombresIn, $ApellidosIn) { $this->IdClientes = $IdClientesIn; $this->Nombres = $NombresIn; $this->Apellidos = $ApellidosIn; } /** * hasEqualMapping-method will compare two Clie ntes 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() != $thi s->IdClientes) { return(false); } if ($valueObject->getNombres() != $this-> Nombres) { return(false); } if ($valueObject->getApellidos() != $this ->Apellidos) { return(false); } return true; } /** * toString will return String object represent ing the state of this * valueObject. This is useful during applicati on development, and * possibly when application is writing object states in textlog. */ function toString() {

Page 27: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

$out = $this->getDaogenVersion(); $out = $out."\nclass Clientes, mapping to t able Clientes\n"; $out = $out."Persistent attributes: \n"; $out = $out."IdClientes = ".$this->IdClient es."\n"; $out = $out."Nombres = ".$this->Nombres."\n "; $out = $out."Apellidos = ".$this->Apellidos ."\n"; return $out; } /** * Clone will return identical deep copy of thi s valueObject. * Note, that this method is different than the clone() which * is defined in java.lang.Object. Here, the re tuned 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 abo ut * generator which created these sources. */ function getDaogenVersion() { return "DaoGen version 2.4.1"; } } ?>

A continuación elabore una archive llamado

"Datasource.php" y reemplácelo por este código

<?php /** * DaoGen MySQL Datasource-object.

Page 28: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

* This class is an helper class to make sure the generated DaoGen * code does not depend on any specific Database-s ystem. * * 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 DaoG en generator version 2.4.1. * The usage of generated code is restricted to Op enSource software projects * only. DaoGen is available in http://titaniclinu x.net/daogen/ * It has been programmed by Tuomo Lukka, Tuomo.Lu [email protected] * * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full te xt for license is available * in GNU project's pages: http://www.gnu.org/copy left/gpl.html * * If you wish to use the DaoGen generator to prod uce code for closed-source * commercial applications, you must pay the lisen ce fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations w ith all supported languages * for each database table you are paying for.) Se nd mail to * "[email protected]" for more information. Than k you! */ class Datasource { var $dbLink; /** * Constructor. Call this once when initiali zing system core. * Then save the instance of this class in $ connection variable * and pass it as an argument when using ser vices from core. */ function Datasource($dbHost, $dbName, $dbuse r, $dbpasswd) { // Change this line to reflect what ever Database system you are using: $this->dbLink = mysql_connect ($dbH ost, $dbuser, $dbpasswd); // Change this line to reflect what ever Database system you are using: mysql_select_db ($dbName, $this->db Link); } /** * Function to execute SQL-commands. Use th is thin wrapper to avoid * MySQL dependency in application code.

Page 29: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

*/ function execute($sql) { // Change this line to reflect what ever Database system you are using: $result = mysql_query($sql, $this-> dbLink); $this->checkErrors($sql); return $result; } /** * Function to "blindly" execute SQL-comman ds. 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 what ever 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 co de. */ function nextRow ($result) { // Change this line to reflect what ever Database system you are using: $row = mysql_fetch_array($result); return $row; } /** * Check if sql-queries triggered errors. T his will be called after an * execute-command. Function requires attem pted SQL string as parameter * since it can be logged to application sp esific log if errors occurred. * This whole method depends heavily from s elected Database-system. Make * sure you change this method when using s ome other than MySQL database. */ function checkErrors($sql) { //global $systemLog;

Page 30: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

// 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 logg ed and aplication will teminate immediately. $message = "The following S QL command ".$sql." caused Database error: ".$err."."; //$message = addslashes("SQ L-command: ".$sql." error-message: ".$message); //$systemLog->writeSystemSq lError ("SQL Error occurred", $errno, $message); print "Unrecowerable error has occurred. All data will be logged."; print "Please contact Syste m Administrator for help! \n"; print "<!-- ".$message." -- >\n"; exit; } else { // Since there was no error , we can safely return to main program. return; } } } ?>

A continuación elabore un archive llamado

"ClientesDao.php" y reemplace el código 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 DaoG en generator version 2.4.1. * The usage of generated code is restricted to Op enSource software projects * only. DaoGen is available in http://titaniclinu x.net/daogen/ * It has been programmed by Tuomo Lukka, Tuomo.Lu [email protected]

Page 31: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

* * DaoGen license: The following DaoGen generated source code is licensed * under the terms of GNU GPL license. The full te xt for license is available * in GNU project's pages: http://www.gnu.org/copy left/gpl.html * * If you wish to use the DaoGen generator to prod uce code for closed-source * commercial applications, you must pay the lisen ce fee. The price is * 5 USD or 5 Eur for each database table, you are generating code for. * (That includes unlimited amount of iterations w ith all supported languages * for each database table you are paying for.) Se nd mail to * "[email protected]" for more information. Than k you! */ class ClientesDao { /** * createValueObject-method. This method is use d when the Dao class needs * to create new value object instance. The rea son why this method exists * is that sometimes the programmer may want to extend also the valueObject * and then this method can be overrided to ret urn extended valueObject. * NOTE: If you extend the valueObject class, m ake 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 v alueObject as a parameter. Returned * valueObject will be created using the create ValueObject() method. */ function getObject(&$conn, $IdClientes) { $valueObject = $this->createValueObject() ; $valueObject->setIdClientes($IdClientes); $this->load(&$conn, &$valueObject); return $valueObject; } /** * load-method. This will load valueObject cont ents from database using * Primary-Key as identifier. Upper layer shoul d use this so that valueObject * instance is created and only primary - key should be specified. Then

Page 32: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

call * this method to complete other persistent inf ormation. This method will * overwrite all other fields except primary-ke y and possible runtime variables. * If load can not find matching row, NotFoundE xception will be thrown. * * @param conn This method requires wor king database connection. * @param valueObject This parameter contains the class instance to be loaded. * Primary-key field must b e set for this to work properly. */ function load(&$conn, &$valueObject) { if (!$valueObject->getIdClientes()) { //print "Can not select without Prim ary-Key!"; return false; } $sql = "SELECT * FROM Clientes WHERE (IdC lientes = '".$valueObject->getIdClientes()."') "; if ($this->singleQuery(&$conn, $sql, &$va lueObject)) return true; else return false; } /** * LoadAll-method. This will read all contents from database table and * build an Vector containing valueObjects. Ple ase note, that this method * will consume huge amounts of resources if ta ble has lot's of rows. * This should only be used when target tables have only small amounts * of data. * * @param conn This method requires wor king database connection. */ function loadAll(&$conn) { $sql = "SELECT * FROM Clientes ORDER BY I dClientes ASC "; $searchResults = $this->listQuery(&$conn, $sql); return $searchResults; } /** * create-method. This will create new row in d atabase according to supplied * valueObject contents. Make sure that values for all NOT NULL columns are * correctly specified. Also, if this table doe s not use automatic surrogate - keys

Page 33: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

* the primary-key must be specified. After INS ERT command this method will * read the generated primary-key back to value Object if automatic surrogate-keys * were used. * * @param conn This method requires wor king database connection. * @param valueObject This parameter contains the class instance to be created. * If automatic surrogate-k eys are not used the Primary-key * field must be set for th is to work properly. */ function create(&$conn, &$valueObject) { $sql = "INSERT INTO Clientes ( IdClientes , Nombres, Apellidos) VALUES ('".$valueObject->getIdClientes()."', "; $sql = $sql."'".$valueObject->getNombres( )."', "; $sql = $sql."'".$valueObject->getApellido s()."') "; $result = $this->databaseUpdate(&$conn, $ sql); return true; } /** * save-method. This method will save the curre nt 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 dat abase. If save can not find matching * row, NotFoundException will be thrown. * * @param conn This method requires wor king database connection. * @param valueObject This parameter contains the class instance to be saved. * Primary-key field must b e 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 = '".$val ueObject->getIdClientes()."') "; $result = $this->databaseUpdate(&$conn, $ sql); if ($result != 1) { //print "PrimaryKey Error when updat ing DB!"; return false; }

Page 34: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

return true; } /** * delete-method. This method will remove the i nformation 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 o nly 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 wor king database connection. * @param valueObject This parameter contains the class instance to be deleted. * Primary-key field must b e set for this to work properly. */ function delete(&$conn, &$valueObject) { if (!$valueObject->getIdClientes()) { //print "Can not delete without Prim ary-Key!"; return false; } $sql = "DELETE FROM Clientes WHERE (IdCli entes = '".$valueObject->getIdClientes()."') "; $result = $this->databaseUpdate(&$conn, $ sql); if ($result != 1) { //print "PrimaryKey Error when updat ing DB!"; return false; } return true; } /** * deleteAll-method. This method will remove al l 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 valueObje ct 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 resul ting object will have different primary-key * than what it was in the deleted object. (Not e, the implementation of this method should * be different with different DB backends.)

Page 35: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

* * @param conn This method requires wor king 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 exe cute "select count(primarykey) from table". * If table is empty, the return value is 0. Th is method should be used before calling * loadAll, to make sure table has not too many rows. * * @param conn This method requires wor king 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 variab les of given object. * Upper layer should use this by setting some parameters in valueObject * and then call searchMatching. The result wi ll be 0-N objects in vector, * all matching those criteria you specified. T hose instance-variables that * have NULL values are excluded in search-crit eria. * * @param conn This method requires wor king 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 Client es WHERE 1=1 ";

Page 36: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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 '".$val ueObject->getNombres()."%' "; } if ($valueObject->getApellidos() != "") { if ($first) { $first = false; } $sql = $sql."AND Apellidos LIKE '".$v alueObject->getApellidos()."%' "; } $sql = $sql."ORDER BY IdClientes ASC "; // Prevent accidential full table results . // Use loadAll if all rows must be return ed. if ($first) return array(); $searchResults = $this->listQuery(&$conn, $sql); return $searchResults; } /** * getDaogenVersion will return information abo ut * generator which created these sources. */ function getDaogenVersion() { return "DaoGen version 2.4.1"; } /** * databaseUpdate-method. This method is a help er method for internal use. It will execute * all database handling that will change the i nformation in tables. SELECT queries will * not be executed here however. The return val ue indicates how many rows were affected. * This method will also make sure that if cach e is used, it will reset when data changes. * * @param conn This method requires wor king database connection. * @param stmt This parameter contains the SQL statement to be excuted. */ function databaseUpdate(&$conn, &$sql) {

Page 37: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

$result = $conn->execute($sql); return $result; } /** * databaseQuery-method. This method is a helpe r method for internal use. It will execute * all database queries that will return only o ne row. The resultset will be converted * to valueObject. If no rows were found, NotFo undException will be thrown. * * @param conn This method requires wor king database connection. * @param stmt This parameter contains the SQL statement to be excuted. * @param valueObject Class-instance where res ulting data will be stored. */ function singleQuery(&$conn, &$sql, &$valueObje ct) { $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 helpe r method for internal use. It will execute * all database queries that will return multip le 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 wor king 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)) {

Page 38: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

$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 reemplácelo por este código:

<?php

require("Datasource.php");// Esta es la clase de la fuente de datos

require("Clientes.php");// Esta es la clase que contiene los métodos 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

}

}

Page 39: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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

}

Page 40: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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";

Page 41: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

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

Page 42: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

?>"></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 aplicación como esta

Page 43: Guia de Desarrollo APACHE + Mysql + PHP y DAO 2012

Actividad: elabore el método modificar y eliminar