Hola y bienvenid@s a este tutorial en donde te enseñaré como crear una app de notas usando PHP y MySQL, usaremos una base de datos de MySQL para almacenar el texto de las notas. Esta pequeña aplicación web es una excelente manera de ver cómo podemos trabajar con PHP y MySQL para crear una simple pero intuitiva app de notas.
En esta aplicación de notas, los usuarios pueden agregar o eliminar fácilmente sus notas. Las notas que el usuario ha agregado a esta aplicación se almacenarán en base de datos MySQL, por lo que no se eliminarán al actualizar o cerrar el navegador web, todo esto se hará utilizando las siguientes tecnologías:
- PHP
- MySQL
- CSS
- JavaScript
- Jquery
- Bootstrap 5
También debes contar con un servidor web local como XAMPP
Crea una aplicación de notas con PHP y MySQL [Código fuente]
Para crear esta aplicación de notas con PHP. Primero, debemos crear un archivo llamado index.html. Después de crear dicho archivos, simplemente copia y pega el código mostrado a continuación.
Archivo index.html
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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Tablero de notas con PHP y MySQL</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"> <div class="page-content container note-has-grid"> <ul class="nav nav-pills p-3 bg-white mb-3 rounded-pill align-items-center"> <li class="nav-item"> <a href="javascript:void(0)" class="nav-link rounded-pill note-link d-flex align-items-center px-2 px-md-3 mr-0 mr-md-2 active" id="all-category"> <i class="icon-layers mr-1"></i><span class="d-none d-md-block">Todas las notas</span> </a> </li> <li class="nav-item"> <a href="javascript:void(0)" class="nav-link rounded-pill note-link d-flex align-items-center px-2 px-md-3 mr-0 mr-md-2" id="note-business"> <i class="icon-briefcase mr-1"></i><span class="d-none d-md-block">Negocios</span></a> </li> <li class="nav-item"> <a href="javascript:void(0)" class="nav-link rounded-pill note-link d-flex align-items-center px-2 px-md-3 mr-0 mr-md-2" id="note-social"> <i class="icon-share-alt mr-1"></i><span class="d-none d-md-block">Social</span></a> </li> <li class="nav-item"> <a href="javascript:void(0)" class="nav-link rounded-pill note-link d-flex align-items-center px-2 px-md-3 mr-0 mr-md-2" id="note-important"> <i class="icon-tag mr-1"></i><span class="d-none d-md-block">Importante</span></a> </li> <li class="nav-item ml-auto"> <a href="javascript:void(0)" class="nav-link btn-info rounded-pill d-flex align-items-center px-3" id="add-notes"> <i class="icon-note m-1"></i><span class="d-none d-md-block font-14">Agregar nota</span></a> </li> </ul> <div class="position-absolute"> <div id="loader"></div> </div> <div id="resultados_ajax"></div> <div class="tab-content bg-transparent"> </div> <form name="guardar_nota" id="guardar_nota" method="post"> <!-- Modal Add notes --> <div class="modal fade" id="addnotesmodal" tabindex="-1" role="dialog" aria-labelledby="addnotesmodalTitle" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content border-0"> <div class="modal-header bg-info text-white"> <h5 class="modal-title text-white">Agregar nota</h5> <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="notes-box"> <div class="notes-content"> <div class="row"> <div class="col-md-12 mb-3"> <div class="note-title"> <label>Título</label> <input type="text" id="note-has-title" name="note-has-title" class="form-control" minlength="10" placeholder="Título" required /> </div> </div> <div class="col-md-12"> <div class="note-description"> <label>Descripción</label> <textarea id="note-has-description" name="note-has-description" class="form-control" minlength="30" placeholder="Descripción" required rows="3"></textarea> </div> </div> </div> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-danger" data-dismiss="modal">Cancelar</button> <button id="btn-n-add" class="btn btn-info" type="submit">Guardar</button> </div> </div> </div> </div> </form> </div> <style type="text/css"> </style> <script type="text/javascript" src="js/app.js"></script> </body> </html> |
En segundo archivo que vamos a crear lo vamos a nombrar style.css, dicho archivo lo colocaremos dentro de una carpeta llamada “css” . este archivo se encarga de darle una mejora visual a nuestra aplicación de notas.
Archivo style.css
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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
body{ background: #edf1f5; margin-top:20px; } .card { position: relative; display: flex; flex-direction: column; min-width: 0; word-wrap: break-word; background-color: #fff; background-clip: border-box; border: 0 solid transparent; border-radius: 0; } .card { margin-bottom: 30px; } .card-body { flex: 1 1 auto; padding: 1.57rem; } .note-has-grid .nav-link { padding: .5rem } .note-has-grid .single-note-item .card { border-radius: 10px } .note-has-grid .single-note-item .favourite-note { cursor: pointer } .note-has-grid .single-note-item .side-stick { position: absolute; width: 3px; height: 35px; left: 0; background-color: rgba(82, 95, 127, .5) } .note-has-grid .single-note-item .category-dropdown.dropdown-toggle:after { display: none } .note-has-grid .single-note-item .category [class*=category-] { height: 15px; width: 15px; display: none } .note-has-grid .single-note-item .category [class*=category-]::after { content: "\f0d7"; font: normal normal normal 14px/1 FontAwesome; font-size: 12px; color: #fff; position: absolute } .note-has-grid .single-note-item .category .category-business { background-color: rgba(44, 208, 126, .5); border: 2px solid #2cd07e } .note-has-grid .single-note-item .category .category-social { background-color: rgba(44, 171, 227, .5); border: 2px solid #2cabe3 } .note-has-grid .single-note-item .category .category-important { background-color: rgba(255, 80, 80, .5); border: 2px solid #ff5050 } .note-has-grid .single-note-item.all-category .point { color: rgba(82, 95, 127, .5) } .note-has-grid .single-note-item.note-business .point { color: rgba(44, 208, 126, .5) } .note-has-grid .single-note-item.note-business .side-stick { background-color: rgba(44, 208, 126, .5) } .note-has-grid .single-note-item.note-business .category .category-business { display: inline-block } .note-has-grid .single-note-item.note-favourite .favourite-note { color: #ffc107 } .note-has-grid .single-note-item.note-social .point { color: rgba(44, 171, 227, .5) } .note-has-grid .single-note-item.note-social .side-stick { background-color: rgba(44, 171, 227, .5) } .note-has-grid .single-note-item.note-social .category .category-social { display: inline-block } .note-has-grid .single-note-item.note-important .point { color: rgba(255, 80, 80, .5) } .note-has-grid .single-note-item.note-important .side-stick { background-color: rgba(255, 80, 80, .5) } .note-has-grid .single-note-item.note-important .category .category-important { display: inline-block } .note-has-grid .single-note-item.all-category .more-options, .note-has-grid .single-note-item.all-category.note-favourite .more-options { display: block } .note-has-grid .single-note-item.all-category.note-business .more-options, .note-has-grid .single-note-item.all-category.note-favourite.note-business .more-options, .note-has-grid .single-note-item.all-category.note-favourite.note-important .more-options, .note-has-grid .single-note-item.all-category.note-favourite.note-social .more-options, .note-has-grid .single-note-item.all-category.note-important .more-options, .note-has-grid .single-note-item.all-category.note-social .more-options { display: none } @media (max-width:767.98px) { .note-has-grid .single-note-item { max-width: 100% } } @media (max-width:991.98px) { .note-has-grid .single-note-item { max-width: 216px } } /*Custom bs5*/ .nav-pills .nav-link.active, .nav-pills .show>.nav-link { color: #fff; background-color: #117a8b; } a { color: #17a2b8; text-decoration: none; background-color: transparent; } .position-absolute{ top:50px; left:50%; transform: translate(-50% , -50%); -webkit-transform: translate(-50%, -50%); } |
Ahora vamos a crear un archivo JavaScript, lo vamos a nombrar app.js, este archivo lo colocaremos dentro de una carpeta llamada “js”. El archivo app.js se encargará de darle un poco de dinamismo a nuestra aplicación web a través de JavaScript, para la creación, lectura, actualización y eliminación de los datos, todo ello utilizando la tecnología AJAX jQuery.
Archivo app.js
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 113 |
$(function() { load(1); }) function load(page){ var q= ""; $("#loader").fadeIn('slow'); $.ajax({ url:'notas_ajax.php?action=ajax&page='+page+'&q='+q, beforeSend: function(objeto){ $('#loader').html('Cargando...'); }, success:function(data){ $(".tab-content").html(data).fadeIn('slow'); $('#loader').html(''); } }) } function eliminar_nota(id) { if (confirm('Realmente deseas eliminar esta nota?')){ page=1; var q= ""; $("#loader").fadeIn('slow'); $.ajax({ url:'notas_ajax.php?action=ajax&page='+page+'&q='+q+'&delete='+id, beforeSend: function(objeto){ $('#loader').html('Cargando...'); }, success:function(data){ $(".tab-content").html(data).fadeIn('slow'); $('#loader').html(''); } }) } } $('#add-notes').on('click', function(event) { $('#addnotesmodal').modal('show'); $('#btn-n-add').show(); }) $( "#guardar_nota" ).submit(function( event ) { var parametros = $(this).serialize(); $.ajax({ type: "POST", url: "agregar_nota.php", data: parametros, beforeSend: function(objeto){ $("#loader").html("Mensaje: Cargando..."); }, success: function(datos){ $("#resultados_ajax").html(datos); $('#loader').html(''); $('#addnotesmodal').modal('hide'); load(1); } }); event.preventDefault(); }) function actualizar_categoria(id,value){ page=1; var q= ""; $("#loader").fadeIn('slow'); $.ajax({ url:'notas_ajax.php?action=ajax&page='+page+'&q='+q+'&actualizar='+id+'&value='+value, beforeSend: function(objeto){ $('#loader').html('Cargando...'); }, success:function(data){ $(".tab-content").html(data).fadeIn('slow'); $('#loader').html(''); } }) } var $btns = $('.note-link').click(function() { if (this.id == 'all-category') { var $el = $('.' + this.id).fadeIn(); $('#note-full-container > div').not($el).hide(); } if (this.id == 'important') { var $el = $('.' + this.id).fadeIn(); $('#note-full-container > div').not($el).hide(); } else { var $el = $('.' + this.id).fadeIn(); $('#note-full-container > div').not($el).hide(); } $btns.removeClass('active'); $(this).addClass('active'); }) |
Como cuarto paso vamos a crear nuestra base de datos MySQL, esto para poder guardar nuestras notas en dicha base de datos. Para crear nuestra base de datos debemos abrir nuestro gestor de base de datos, en mi caso estoy usando phpMyAdmin, abrimos phpMyAdmin y creamos una base de datos llamada: test_app_notas (para efectos de ejemplo la he nombrado así, pero tu puedes llamarla como desees), luego abrimos la base de datos recientemente creada y ejecutamos el siguiente código SQL.
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 |
CREATE TABLE `notas` ( `id` int(11) NOT NULL, `titulo` varchar(100) NOT NULL, `descripcion` varchar(255) DEFAULT NULL, `fecha` datetime NOT NULL, `categoria` varchar(100) NOT NULL DEFAULT 'social' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `notas` -- ALTER TABLE `notas` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `notas` -- ALTER TABLE `notas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; |
Ahora vamos a crear un archivo que nos servirá para conectarnos a la base de datos MySQL, lo llamaremos conexionDB.php
Archivo conexionDB.php
1 2 3 4 5 6 7 |
<?php # conectare la base de datos $host="localhost"; $user="root"; $pass=''; $db_name="test_app_notas"; $link=mysqli_connect($host, $user, $pass, $db_name); |
Asegúrate de asignar los datos de conexión pertenecientes a tu servidor, si en el paso anterior de creación de la base de datos, nombraste de forma distinta la base de datos, entonces modifica la línea 5 y a la variable llamada $db_name asígnale el nombre de la base de datos que nombraste.
Ahora nos toca leer la información de las notas almacenadas en nuestra base de datos, para ello creamos el archivo notas_ajax.php
Archivo notas_ajax.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 |
<?php $action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:''; if($action == 'ajax'){ include("conexionDB.php"); $sTable = "notas"; $sWhere = " order by id desc"; if (isset($_REQUEST['delete'])){ $id_nota=intval($_REQUEST['delete']); $delete=mysqli_query($link,"delete from $sTable where id='$id_nota'"); } if (isset($_REQUEST['actualizar'])){ $id_nota=intval($_REQUEST['actualizar']); $value=intval($_REQUEST['value']); if ($value==1){ $cat='business'; } else if ($value==2){ $cat='social'; } else if ($value==3){ $cat='important'; } else { $cat=''; } $update=mysqli_query($link,"update $sTable set categoria='$cat' where id='$id_nota'"); } $sql="SELECT * FROM $sTable $sWhere "; $query = mysqli_query($link, $sql); $num=mysqli_num_rows($query); if ($num>0){ ?> <div id="note-full-container" class="note-has-grid row"> <?php while($row=mysqli_fetch_array($query)){ ?> <div class="col-md-4 single-note-item all-category note-<?=$row['categoria'];?> " style=""> <div class="card card-body "> <span class="side-stick"></span> <h5 class="note-title text-truncate w-80 mb-0" data-noteheading="<?=$row['titulo'];?>"><?=$row['titulo'];?> <i class="point fa fa-circle ml-1 font-10"></i></h5> <p class="note-date font-12 text-muted"><?=date('d/m/Y',strtotime($row['fecha']));?></p> <div class="note-content"> <p class="note-inner-content text-muted" data-notecontent="<?=$row['descripcion'];?>"><?=$row['descripcion'];?></p> </div> <div class="d-flex align-items-center"> <a href="#" onclick="eliminar_nota('<?=$row['id'];?>')"> <span class="mr-1"><i class="fa fa-trash text-danger"></i></span></a> <div class="ml-auto"> <div class="category-selector btn-group"> <a class="nav-link dropdown-toggle category-dropdown label-group p-0" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="true"> <div class="category"> <div class="category-business"></div> <div class="category-social"></div> <div class="category-important"></div> <span class="more-options text-dark"><i class="icon-options-vertical"></i></span> </div> </a> <div class="dropdown-menu dropdown-menu-right category-menu"> <a class="note-business badge-group-item badge-business dropdown-item position-relative category-business text-success" href="javascript:void(0);" onclick="actualizar_categoria('<?=$row['id'];?>','1');"> <i class="mdi mdi-checkbox-blank-circle-outline mr-1" ></i>Negocios </a> <a class="note-social badge-group-item badge-social dropdown-item position-relative category-social text-info" href="javascript:void(0);" onclick="actualizar_categoria('<?=$row['id'];?>','2');"> <i class="mdi mdi-checkbox-blank-circle-outline mr-1" ></i> Social </a> <a class="note-important badge-group-item badge-important dropdown-item position-relative category-important text-danger" href="javascript:void(0);" onclick="actualizar_categoria('<?=$row['id'];?>','3');"> <i class="mdi mdi-checkbox-blank-circle-outline mr-1" ></i> Importante </a> </div> </div> </div> </div> </div> </div> <?php } ?> </div> <?php } } ?> |
Finalmente vamos a crear el archivo que se encarga de guardar la notas en la base de datos, este archivo lo nombraremos agregar_nota.php
Archivo agregar_nota.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 |
<?php /*Inicia validacion del lado del servidor*/ if (empty($_POST['note-has-title'])) { $errors[] = "Ingresa el título de la nota"; } else if (!empty($_POST['note-has-title'])){ /* Connect To Database*/ require_once ("conexionDB.php");//Contiene funcion que conecta a la base de datos // escaping, additionally removing everything that could be (html/javascript-) code $titulo=mysqli_real_escape_string($link,(strip_tags($_POST["note-has-title"],ENT_QUOTES))); $descripcion=mysqli_real_escape_string($link,(strip_tags($_POST["note-has-description"],ENT_QUOTES))); $date_added=date("Y-m-d H:i:s"); $sql="INSERT INTO `notas` (`id`, `titulo`, `descripcion`, `fecha`, `categoria`) VALUES (NULL, '$titulo', '$descripcion', '$date_added', 'social');"; $query_new_insert = mysqli_query($link,$sql); if ($query_new_insert){ $messages[] = "Nota ha sido ingresada satisfactoriamente."; } else{ $errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($link); } } else { $errors []= "Error desconocido."; } if (isset($errors)){ ?> <div class="alert alert-danger" role="alert"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Error!</strong> <?php foreach ($errors as $error) { echo $error; } ?> </div> <?php } if (isset($messages)){ ?> <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>¡Bien hecho!</strong> <?php foreach ($messages as $message) { echo $message; } ?> </div> <?php } ?> |
Llegado a este punto así es como se vería la interfaz grafica de nuestra aplicación de notas.
Esto sería todo, ahora haz creado con éxito una aplicación de notas con PHP y MySQL. Puedes conseguir el código funcional si sigues cada uno de los pasos detallados en este tutorial.
Si tu código no funciona o haz tenido algún problema, tienes la opción de hacer una pequeña donación y descargar los archivos del código fuente usando el botón de descarga indicado a continuación .
Ver demostración Descargar archivos