Voy a mostrar como insertar contenido html a una base de datos MySQL, con PHP, para ello vamos a realizar una serie de pasos para obtener nuestro simple pero muy útil gestor de contenido. Veamos como se hace:
Paso 1: Crear plantilla html usando el Framework Bootstrap y llamaremos a dicha plantilla “index.php“. A continuación muestro el código.
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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <title>Gestor de contenidos con Bootstrap</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <style> body { min-height: 2000px; padding-top: 70px; } </style> </head> <body> <!-- Fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Gestor de contenidos bootstrap</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.php">Inicio</a></li> <li ><a href="entradas.php">Entradas</a></li> <li><a href="contenido.php">Contenido</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> <div class="jumbotron"> <form method="post"> <div class="form-group"> <label for="post_title">Titulo de la entrada</label> <input type="text" class="form-control" id="post_title" name="post_title" placeholder="Ingesa el titulo de la entrada" required> </div> <div class="form-group"> <label for="post_content">Contenido de la entrada</label> <textarea name="post_content" id="post_content" class="form-control" rows="20" cols="80" placeholder="Ingresa contenido de la entrada"> </textarea> </div> <button type="submit" class="btn btn-success" name="guardar">Publicar entrada</button> </form> </div> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> </body> </html> |
Paso 2: Descargar el Plugins openmanagerdemo y descomprimirlo, luego copiar las carpetas “jscripts” y “uploads” en la misma ruta donde creamos el archivo “index.php“.
Paso 3: Configurar el Plugins “TinyMCE’ para que funciones nuestro editor de texto enriquecido. Agregaremos la siguintes lineas de código JavaScript antes de la etiqueta de cierre del </body> dentro del archivo “index.php” previamente creado:
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 |
<!-- TinyMCE --> <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options relative_urls: false, remove_script_host : false, convert_urls : true, extended_valid_elements : "video[*]", mode : "textareas", theme : "advanced", skin : "bootstrap", plugins : "openmanager,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,visualblocks", // Theme options theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,visualblocks,|,openmanager", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, //Open Manager Options file_browser_callback: "openmanager", open_manager_upload_path: '../../../../uploads/', // Example content CSS (should be your site CSS) content_css : "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", // Drop lists for link/image/media/template dialogs template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js", // Style formats style_formats : [ {title : 'Bold text', inline : 'b'}, {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}}, {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}}, {title : 'Example 1', inline : 'span', classes : 'example1'}, {title : 'Example 2', inline : 'span', classes : 'example2'}, {title : 'Table styles'}, {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'} ], }); </script> <!-- /TinyMCE --> |
Paso 4: Agregamos TinyMCE skin Twitter Bootstrap, para cambiar el aspecto de los botones del editor. Descargar Plugin AQUI, Y descomprimir el contenido de la carpeta llamada bootstrap en la siguiente ruta: jscripts > tiny_mce > themes > advanced > skins
Paso 5: Procedemos a crear la base de datos en php MyAdmin, para el ejemplo la llamaremos “gestor_contenido”, a continuación se creará una tabla donde se almacenará el contenido.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
-- -- Estructura de tabla para la tabla `post` -- CREATE TABLE IF NOT EXISTS `post` ( `id_contenido` int(11) NOT NULL, `post_title` longtext NOT NULL, `post_content` longtext NOT NULL, `date_added` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `post` -- ALTER TABLE `post` ADD PRIMARY KEY (`id_contenido`); |
Paso 6: Dentro de la carpeta root crear una carpeta llama “db“, que es allí donde se colocará los datos de conexión a la base de datos y nombraremos dicho archivo “conexion.php”.
1 2 3 4 5 6 7 8 9 10 |
<?php # conectare la base de datos $con=@mysqli_connect("localhost", "root", "root", "gestor_contenido"); if(!$con){ die("imposible conectarse: ".mysqli_error($con)); } if (@mysqli_connect_errno()) { die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); } ?> |
Paso 7: Almacenar el contenido en la base de datos. Antes de la etiqueta <form>, que se encuentra en nuestro archivo index.php colocar el siguiente fragmento de código
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 if (isset($_POST["guardar"])){ include("db/conexion.php"); if (empty($_POST['post_title'])){ $errors[]="Ingresa el titulo de la entrada."; } else if (empty($_POST['post_content'])){ $errors[]="Ingresa el contenido de la entrada."; } else if (!empty($_POST['post_title']) && !empty($_POST['post_content'])){ $post_title=htmlspecialchars( stripslashes((string)$_POST["post_title"]) ); $post_content = htmlspecialchars( stripslashes((string)$_POST["post_content"]) ); $date_added=date("Y-m-d H:i:s"); $sql="INSERT INTO post (post_title, post_content, date_added) VALUES ('".$post_title."', '".$post_content."', '".$date_added."')"; $query_insert=mysqli_query($con, $sql); if ($query_insert){ $messages[] = "Los datos se han procesado con satisfactoriamente."; } else { $errors[] = "No se ha podido guardar los datos. ".mysqli_error($con); } } if (isset($errors)) { ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <strong>Error!</strong> <?php foreach ($errors as $error) { echo $error; } ?> </div> <?php } if (isset($messages)) { ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <strong>Bien hecho!</strong> <?php foreach ($messages as $message){ echo $message; } ?> </div> <?php } } ?> |
Paso 8: Uniendolo todo: Nuestro archivo index.php debería quedar de la siguiente manera.
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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
<?php date_default_timezone_set('America/El_Salvador');//Hora formato de El Salvador ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <title>Gestor de contenidos con Bootstrap</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <style> body { min-height: 2000px; padding-top: 70px; } </style> </head> <body> <!-- Fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Gestor de contenidos bootstrap</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.php">Inicio</a></li> <li ><a href="entradas.php">Entradas</a></li> <li><a href="contenido.php">Contenido</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> <div class="jumbotron"> <?php if (isset($_POST["guardar"])){ include("db/conexion.php"); if (empty($_POST['post_title'])){ $errors[]="Ingresa el titulo de la entrada."; } else if (empty($_POST['post_content'])){ $errors[]="Ingresa el contenido de la entrada."; } else if (!empty($_POST['post_title']) && !empty($_POST['post_content'])){ $post_title=htmlspecialchars( stripslashes((string)$_POST["post_title"]) ); $post_content = htmlspecialchars( stripslashes((string)$_POST["post_content"]) ); $date_added=date("Y-m-d H:i:s"); $sql="INSERT INTO post (post_title, post_content, date_added) VALUES ('".$post_title."', '".$post_content."', '".$date_added."')"; $query_insert=mysqli_query($con, $sql); if ($query_insert){ $messages[] = "Los datos se han procesado con satisfactoriamente."; } else { $errors[] = "No se ha podido guardar los datos. ".mysqli_error($con); } } if (isset($errors)) { ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <strong>Error!</strong> <?php foreach ($errors as $error) { echo $error; } ?> </div> <?php } if (isset($messages)) { ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <strong>Bien hecho!</strong> <?php foreach ($messages as $message){ echo $message; } ?> </div> <?php } } ?> <form method="post"> <div class="form-group"> <label for="post_title">Titulo de la entrada</label> <input type="text" class="form-control" id="post_title" name="post_title" placeholder="Ingesa el titulo de la entrada" required> </div> <div class="form-group"> <label for="post_content">Contenido de la entrada</label> <textarea name="post_content" id="post_content" class="form-control" rows="20" cols="80" placeholder="Ingresa contenido de la entrada"> </textarea> </div> <button type="submit" class="btn btn-success" name="guardar">Publicar entrada</button> </form> </div> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <!-- TinyMCE --> <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options relative_urls: false, remove_script_host : false, convert_urls : true, extended_valid_elements : "video[*]", mode : "textareas", theme : "advanced", skin : "bootstrap", plugins : "openmanager,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,visualblocks", // Theme options theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,visualblocks,|,openmanager", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, //Open Manager Options file_browser_callback: "openmanager", open_manager_upload_path: '../../../../uploads/', // Example content CSS (should be your site CSS) content_css : "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", // Drop lists for link/image/media/template dialogs template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js", // Style formats style_formats : [ {title : 'Bold text', inline : 'b'}, {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}}, {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}}, {title : 'Example 1', inline : 'span', classes : 'example1'}, {title : 'Example 2', inline : 'span', classes : 'example2'}, {title : 'Table styles'}, {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'} ], }); </script> <!-- /TinyMCE --> </body> </html> |
En los tutoriales siguientes les mostraré como editar el contenido, eliminar contenido y como se verá el contenido insertado como un blog de noticias y comentarios. La versión demostrativa y el código fuente completo lo pondrán descargar al finalizar el Tutorial completamente.
Espero sus comentarios o sus sugerencias 🙂