Ticker

6/recent/ticker-posts

CodeIgniter - Aplicación Web CRUD

En este tutorial práctico desarrollaremos una Aplicación Web CRUD haciendo uso del Framework PHP como es CodeIgniter, se implementará haciendo uso de la versión 3 de CodeIgniter en base a las sentencias de SQL con conexión a la base de datos relacional como es MySQL.

Requisitos:

  1. XAMPP Control Panel.
  2. MySQL Workbench o phpMyAdmin.
  3. Visual Studio Code
  4. CodeIgniter v3 (Framework PHP)
  5. Bootstrap 5 (HTML5 y CSS3)

Lo que veremos en este tutorial:

  1. Descargar CodeIgniter v3.
  2. Crear la base de datos en MySQL.
  3. Configurar archivos de la aplicación.
  4. Crear e implementar modelo.
  5. Crear e implementar controlador.
  6. Crear e implementar vista.
  7. Conclusiones.

1. Descargar CodeIgniter v3.

Para la descarga del Framework CodeIgniter, sugiero descargar desde la pagina oficial; para este tutorial práctico se hará uso de la versión 3.1.11.

Seguidamente se debe descomprimir el archivo y copiar los archivos en el directorio final donde se iniciará la implementación, en mi caso el directorio final es crud-app-web.

Recuerda que debes levantar los servicios de Apache y MySQL desde el XAMPP Control Panel y el directorio final del proyecto debe estar creado en el htdocs.


2. Crear la base de datos en MySQL.

Crea la base de datos con el nombre de demo desde el Workbench o phpMyAdmin, seguidamente crea la tabla employee con la siguiente estructura:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
--
-- Estructura de tabla para la tabla `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `age` int(2) NOT NULL,
  `email_id` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- PRIMARY KEY de la tabla `employee`
--
ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de la tabla `employee`
--
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

3. Configurar archivos de la aplicación.

Después de crear la base de datos, seguidamente pasamos a configurar los archivos en relación al ecosistema del Framework CodeIgniter:

3.1. Se agregará la url base de nuestro proyecto en el parámetro $config['base_url']  del archivo config.php:

    RUTA DEL ARCHIVO: ..\crud-app-web\application\config\config.php

    PARAMÉTRO: $config['base_url'] = 'http://localhost/crud-app-web/';

3.2. Asignar los valores de conexión a la base de datos en relación a los CONTROLADORES para la conexión a MySQL desde el archivo database.php:

    RUTA DEL ARCHIVO: ..\crud-app-web\application\config\database.php

    PARAMÉTROS:
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'dbdriver' => 'mysqli',


3.3. Asignar el controlador inicial por defecto desde el archivo routes.php:

    ..\crud-app-web\application\config\routes.php
    $route['default_controller'] = 'crud';

Recuerden que nuestro directorio crud-app-web debe estar creada en el directorio htdocs (..\xampp\htdocs) en relación a nuestro servidor web Apache que nos proporciona XAMPP.

4. Crear e implementar modelo.

Crear el modelo de nombre Crud_model.php en el directorio models de nuestro proyecto crud-app-web\application\models e implementar las funciones necesarias (las explicaciones están en la cabecera de cada función o acción que se realiza) para el acceso a datos y realizar la funcionalidad CRUD. Hacer de su conocimiento, acerca de las funciones que se crean en este modelo están orientados a sentencias SQL, es decir, no se esta usando funcionalidades que nos provee el mismo CodeIgniter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

class Crud_model extends CI_Model{
	/* Constuct access database */
	public function __construct(){
		parent::__construct();
		$this->load->database();
	}

    /* Function: insert (create) data on the table employee */
    public function create($first,$last,$email,$gender,$age){
        $query = $this->db->query("insert into employee (first_name,last_name,gender,age,email_id) 
                                    values('$first','$last','$gender','$age','$email')");
            if($query){
                return "success";
            }else{
                return "failed";
            }
    }
    /* Function: select (read) all row or data from table employee */
    public function read(){ 
        $query = $this->db->query("SELECT case e.gender 
                                    WHEN 'm' THEN 'Masculino' 
                                    WHEN 'f' THEN 'Femenino' 
                                    END as gend, e.* FROM employee e;");
        return $query;
    }
    /* Function: select (get_record_byID) record by employee id from table employee */
    public function get_record_byID($id){
        $query = $this->db->query("select * from employee where id='$id'");
        return $query->row();
    }

    /* Funtion: update record by employee id from table employee */
    public function update($first,$last,$email,$gender,$age,$id){
		$query = $this->db->query("UPDATE `employee` SET first_name='$first', last_name='$last',
                                            email_id='$email', gender='$gender', age=$age WHERE id=$id");
	
		if($query){
			return "success";
		}else{
			return "failed";
		}
	}
    /* Funtion: delete row by employee id */
    public function delete($id){
        $query = $this->db->query("delete from employee where id ='$id'");
        if($query){
            return "success";
        }else{
            return "failed";
        }
    }

}

Los modelos son clases que están diseñadas para trabajar con información en relación a la base de datos.

5. Crear e implementar controlador.

Crear el controlador de nombre Crud.php en el directorio controllers de nuestro proyecto crud-app-web\application\controllers:

Implementar las funciones necesarias para cumplir con la lógica en nuestro controlado con la finalidad de logra nuestra funcionalidad CRUD; recuerde, que las explicaciones están en la cabecera de cada función o acción que se realiza:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Crud extends CI_Controller {

    //function for start the contruct: load helper and model
    public function __construct(){
        parent::__construct();
        $this->load->helper('url');
        $this->load->model('crud_model');
    }

    //function for load of views template them and home
    //first page or view home when load web application
    public function index()
    {
    	//$this->load->view('welcome_message');
        $this->load->view("theme/head");
        $this->load->view("crud/home");
        $this->load->view("theme/footer");
    }

    //function for load of views template them and create
    //page or view for input register data the employees
    public function create(){
    	$this->load->view("theme/head");
        $this->load->view("crud/create");
        $this->load->view("theme/footer");
    }

    //function post for process create the registers of employees
    public function create_post(){
        $first_name = $this->input->post('fname');
        $last_name = $this->input->post('lname');
        $email = $this->input->post('email');
        $gender = $this->input->post('gender');
        $age = $this->input->post('age');

        // invocate model and method create
        $res = $this->crud_model->create($first_name,$last_name,$email,$gender,$age);

        // start validate
		if($res == "success"){
			redirect(site_url('crud/read'));// ok, invocate function read (list)
		}else{
			redirect(site_url('crud/create_failed')); //error: invocate function create_failed()
		}
    }

    //function about message of error control for create
    public function create_failed(){
        echo "Error al registrar";
    }
    
    //function for list the data of employees after finalized the process of create the registers
    public function read(){
        $data['res_id'] = $this->crud_model->read();
        $this->load->view("theme/head");
        $this->load->view('crud/view',$data);
        $this->load->view("theme/footer");
    }

    //function for load the data of employee according to id
    public function update($id){
        $data['crud_data'] = $this->crud_model->get_record_byID($id);
        if(!empty($data['crud_data'])){
            $this->load->view("theme/head");
            $this->load->view('crud/update',$data);
            $this->load->view("theme/footer");
        }else{
            redirect(site_url());
        }
    }

    //function post for process update the registers of employees
    public function update_post(){
		$first_name = $this->input->post('fname');
		$last_name = $this->input->post('lname');
		$email = $this->input->post('email');
		$gender = $this->input->post('gender');
		$age = $this->input->post('age');
		$id = $this->input->post('id');

        // invocate model and method update
		$res = $this->crud_model->update($first_name,$last_name,$email,$gender,$age,$id);
		if($res == "success"){
            redirect(site_url('crud/read'));// ok, invocate function read (list)			
		}else{
			redirect(site_url('crud/update_failed'));//error: invocate function update_failed()
		}
	}

    //function about message of error control for update
    public function update_failed(){
        echo "Error al actualizar";
    }       

    public function delete($id){
        // invocate model and method delete
        $res = $this->crud_model->delete($id);
        if($res == "success"){
            redirect(site_url('crud/read'));// ok, invocate function read (list)
        }else{
            redirect(site_url('crud/delete_failed'));//error: invocate function delete_failed()
        }
    }

    //function about message of error control for delete
    public function delete_failed(){
        echo "Error al eliminar";
    }
}

Un controlador (controller) simplemente es un archivo de tipo clase cuyo nombre se asociar con una URI determinada.

6. Crear e implementar vista.

Crear las vistas en el directorio views de nuestro proyecto, en mi caso e creado el sub directorio llamado crud - finalmente crearemos las vistas de home.phpcreate.phpview.php y update.php:

crud-app-web\application\views\crud\home.php

1
2
3
4
<div class="text-center">

    <a class="btn btn-info" href="<?= base_url('crud/create'); ?>" role="button">Ingresar Registro</a>   
</div>

crud-app-web\application\views\crud\create.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
<div class="container">
	<div class="row">
		<form method="post" class="form-horizontal col-md-6 col-md-offset-3" id="frmSave"
                action="<?php echo site_url('crud/create_post'); ?>">
		    
            <div class="col-lg-12 text-center">
              <div>
                <h1>Registrar Empleado</h1> </br>          	
              </div>
            </div>


			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Nombres</label>
			    <div class="col-sm-10">
			      <input type="text" name="fname"  class="form-control" id="fname" placeholder="Nombres" />
			    </div>
			</div>

			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Apellidos</label>
			    <div class="col-sm-10">
			      <input type="text" name="lname"  class="form-control" id="lname" placeholder="Apellidos" />
			    </div>
			</div>

			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Email</label>
			    <div class="col-sm-10">
			      <input type="email" name="email"  class="form-control" id="email" placeholder="Email" />
			    </div>
			</div>

			<div class="form-group" class="radio">
			<label for="input1" class="col-sm-2 control-label">Sexo</label>
			<div class="col-sm-10">
			  <label>
			    <input type="radio" name="gender" id="optionsRadios1" value="m" checked> Masculino
			  </label>
			  	  <label>
			    <input type="radio" name="gender" id="optionsRadios1" value="f"> Femenino
			  </label>
			</div>
			</div>

			<div class="form-group">
				<label for="input1" class="col-sm-2 control-label">Edad</label>
				<div class="col-sm-10">
					<select name="age" id="age" class="form-control">
						<option value="-1">Seleccionar Edad</option>
            	        <option value="18">18</option>
            	        <option value="19">19</option>
            	        <option value="20">20</option>
						<option value="21">21</option>
						<option value="22">22</option>
						<option value="23">23</option>
						<option value="24">24</option>
						<option value="25">25</option>
            	        <option value="26">26</option>
            	        <option value="27">27</option>
            	        <option value="28">28</option>
            	        <option value="29">29</option>
            	        <option value="30">30</option>                    
					</select>
				</div>
			</div>
			
			<div class="form-group">
				<div class="row text-right">
			    <div class="col-sm-5">
					<a class="btn btn-success" href="<?= base_url('crud/read'); ?>" role="button">Ver</a>
			    </div>
				<div class="col-sm-5">
					<input type="submit" class="btn btn-primary" value="Guardar" />						
				</div>
			</div>

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

<script>


	document.addEventListener("DOMContentLoaded", function() {
  		document.getElementById("frmSave").addEventListener('submit', validarFormulario); 
	});
	
	function validarFormulario(evento) {
	  evento.preventDefault();
	  var vage = document.getElementById('age').value;

	  if (vage == "-1"){
		alert('Seleccionar Edad');
		return;
	  }
	  this.submit();
	}

</script>

crud-app-web\application\views\crud\view.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<div class="container">
	<div class="row">	

		<div class="col-lg-12 text-center">
		  <div>
		    <h1>Leer Empleados</h1> </br>          	
		  </div>
		</div>

		<table class="table "> 
		<thead> 
			<tr> 
				<th>#</th> 
				<th>Nombres y Apellidos</th> 
				<th>Email</th> 
				<th>Sexo</th> 
				<th>Edad</th> 
				<th>Accion</th>
			</tr> 
		</thead> 
        <tbody> 
	        <?php 
            foreach($res_id->result() as $row){
            ?>
            	<tr> 
            		<th scope="row"><?php echo $row->id; ?></th> 
            		<td><?php echo $row->first_name . " " . $row->last_name; ?></td> 
            		<td><?php echo $row->email_id; ?></td> 
            		<td><?php echo $row->gend ?></td> 
            		<td><?php echo $row->age ?></td> 
            		<td>
            			<a href="update/<?php echo $row->id; ?>"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>
            			<a href="delete/<?php echo $row->id; ?>"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
            		</td>
            	</tr> 
            <?php } ?>
        </tbody>
		</table>
	</div>

	<a class="btn btn-success col-md-2 col-md-offset-10" href="<?= base_url('crud/create'); ?>" role="button">Regresar</a>
	
</div>

crud-app-web\application\views\crud\update.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<div class="container">
	<div class="row">
	<form method="post" class="form-horizontal col-md-6 col-md-offset-3" action="<?php echo site_url('crud/update_post')?>">
		
		<div class="col-lg-12 text-center">
		  <div>
		    <h1>Actualizar Empleado</h1> </br>          	
		  </div>
		</div>

		
			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Nombres</label>
			    <div class="col-sm-10">
			      <input type="text" name="fname" value="<?php echo $crud_data->first_name; ?>" class="form-control" id="fname" placeholder="Nombres"/>
			    </div>
			</div>
		
			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Apellidos</label>
			    <div class="col-sm-10">
			      <input type="text" name="lname" value="<?php echo $crud_data->last_name; ?>" class="form-control" id="lname" placeholder="Apellidos" />
			    </div>
			</div>
		
			<div class="form-group">
			    <label for="input1" class="col-sm-2 control-label">Email</label>
			    <div class="col-sm-10">
			      <input type="email" name="email" value="<?php echo $crud_data->email_id; ?>" class="form-control" id="email" placeholder="Email" />
			    </div>
			</div>
		
			<div class="form-group" class="radio">
			<label for="input1" class="col-sm-2 control-label">Sexo</label>
			<div class="col-sm-10">
			  <label>
			    <input type="radio" name="gender" id="optionsRadios1" <?php if($crud_data->gender == 'm'){ echo "checked";} ?> value="m"> Masculino
			  </label>
			  	  <label>
			    <input type="radio" name="gender" id="optionsRadios1" <?php if($crud_data->gender == 'f'){ echo "checked";} ?> value="f"> Femenino
			  </label>
			</div>
			</div>
		
			<div class="form-group">
			<label for="input1" class="col-sm-2 control-label">Edad</label>
			<div class="col-sm-10">
				<select name="age" class="form-control">
					<option>Seleccionar Edad</option>
					<option value="18" <?php if($crud_data->age == 20){ echo "selected";} ?>>18</option>
					<option value="19" <?php if($crud_data->age == 20){ echo "selected";} ?>>19</option>					
					<option value="20" <?php if($crud_data->age == 20){ echo "selected";} ?>>20</option>
					<option value="21" <?php if($crud_data->age == 21){ echo "selected";} ?>>21</option>
					<option value="22" <?php if($crud_data->age == 22){ echo "selected";} ?>>22</option>
					<option value="23" <?php if($crud_data->age == 23){ echo "selected";} ?>>23</option>
					<option value="24" <?php if($crud_data->age == 24){ echo "selected";} ?>>24</option>
					<option value="25" <?php if($crud_data->age == 25){ echo "selected";} ?>>25</option>
					<option value="26" <?php if($crud_data->age == 26){ echo "selected";} ?>>26</option>
					<option value="27" <?php if($crud_data->age == 27){ echo "selected";} ?>>27</option>
					<option value="28" <?php if($crud_data->age == 28){ echo "selected";} ?>>28</option>
					<option value="29" <?php if($crud_data->age == 29){ echo "selected";} ?>>29</option>
					<option value="30" <?php if($crud_data->age == 30){ echo "selected";} ?>>30</option>			
				</select>
			</div>
			</div>
			<input type="hidden" value="<?php echo $crud_data->id; ?>"  name="id" />
			<input type="submit" class="btn btn-primary col-md-2 col-md-offset-10" value="Actualizar" />
		</form>
	</div>
</div>


Recordemos que también se crearon las vista template footer y head en el sub directorio theme.


7. Conclusiones

En base a sentencias SQL nativa realizamos el proceso de creación, modificación  y lectura de datos desde la base de datos, es decir, CodeIgniter como Framework nos facilita hacer uso de sus propias funcionalidades o sentencias nativas como SQL desde el controlador.

Disponible en GitHub


Gracias nuevamente 😊; comentarios y apreciaciones son bienvenido, un fuerte abrazo para todos ✌...!!!

Publicar un comentario

0 Comentarios