Todos sabemos lo tedioso de crear un formulario para ingreso o modificación de una base de datos, este pequeño script nos alivia de esa tarea, otorgandonos el código HTML del formulario y la sentencia SQL (MySql) para su inserción.
Consta de 3 archivos
config.ini
; Parámetros de conexión a Base de Datos
; Debe indicar los siguientes valores
; $usuario_bd = Nombre de usuario con permisos a la base de datos
; $base_de_datos = Nombre de la base de datos que será afectada
; $clave_acceso_bd = Clave del usuario de la base de datos
; $servidor = Dirección de servidor Normalmente es localhost
;
; Sustituya los valores pertinentes
; Importante debe encerrar los valores entre " "
;
[config]
servidor = "localhost"
usuario_bd = "ELUSUARIO"
clave_acceso_bd = "LACLAVE"
base_de_datos = "TUBASEDEDATOS"
conexion.php
<?php
/*
Diseño y programación
Hector A. Mantellini
http://www.sourcecode.com.ve
http://xombra.com
El sistema esta bajo los términos y Licencia
GNU GENERAL PUBLIC LICENSE
Ver Terminos en:
http://gugs.sindominio.net/gnu-gpl/gples.html
CONECTAR A LA DB
IMPORTANTE NO TOCAR NADA DE AQUI */
// sanita de valores
function elimina_slash($valor) {
if (get_magic_quotes_gpc()) {
$valor= stripslashes($valor); }
return $valor;
}
function filter($string) {
$replace = "%20";
$search = array(">", "<", "|", ";", "-","'","&");
$result = str_replace($search, $replace, $string);
return $result;
}
// fin sanita
$matriz_ini = parse_ini_file("config.ini");
$indice = 0;
while (list($key, $val) = each($matriz_ini)) {
$parametro[$indice] = $val;
$indice++;
}
$conexion = @mysql_connect($parametro[0],$parametro[1], $parametro[2])
or die("Error en Conexión a Servidor de Base de datos");
@mysql_select_db($parametro[3], $conexion)
or die("Error en Conexión a Base de datos");
$_SERVER["QUERY_STRING"] = filter(elimina_slash(trim(html_entity_decode($_SERVER["QUERY_STRING"],ENT_QUOTES))));
?>
crear_form.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Creación de Formularios de tablas MySql</title>
</head>
<?php
/*
Diseño y programación
Hector A. Mantellini
SourceCode Consultants, C.A.
http://www.sourcecode.com.ve
Xombra
http://xombra.com
Director Asistente PHP de Venezuela
http://www.php.com.ve
El sistema esta bajo los términos y Licencia
GNU GENERAL PUBLIC LICENSE
Ver Terminos en:
http://www.gnu.org/copyleft/gpl.html
Traducción al español:
http://gugs.sindominio.net/gnu-gpl/gples.html
Versión 0.2
FAVOR LEER config.ini
*/
include 'conexion.php';
?>
<style type="text/css">
<!--
body {
margin-left: 10px;
margin-top: 0px;
}
.style2 {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
color: #FFFFFF;
}
.style3 {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #006699;
background-color: #CCCCCC;
}
.style4 {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size: 9px;
font-style: italic;
}
.style5 {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
font-style:normal;
color: #000000;
}
.style6 {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
font-style:normal;
color: #FF0000;
}
.style10 {
color: #FF0000;
font-weight: bold;
font-size: 18px;
}
.boton {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: bold;
color: #000000;
text-decoration: none; }
.campo {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
line-height: normal;
font-weight: bold;
color: #000000;
text-decoration: none;
}
-->
</style>
</head>
<body>
<table width="57%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="25" align="center" valign="middle" bgcolor="#006699" class="style2">
Creación de Formularios Dinámicos </td>
</tr>
<tr>
<td height="35" align="left" valign="middle" class="style3">
<?php
if (empty($_POST['hacer'])) { ?>
<p>Indique la TABLA MySql a la cual se le creará el formulario <br />
<?php }
else
{ print "<p>Creado formulario para la tabla [ <b><span class=\"style6\"> $_POST[nombre_tabla]</span></b> ]<br />\r\n"; } ?>
</p></td>
</tr>
<tr>
<td>
<?php
if (empty($_POST['hacer'])) { ?>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post" name="tablas" target="_self" >
<label>
<p class="style5">
<?php
$sql = sprintf("SHOW TABLES");
$query = @mysql_query($sql,$conexion);
print "<hr>
Tablas que conforman a Base de Datos: >>> <b><u> $parametro[3] </u></b> <<<
<br><hr><br>\r\n";
print "Indique la tabla a crear formulario<br><br>\r\n";
while ($tabla = @mysql_fetch_array($query)) {
print "<input name=\"nombre_tabla\" class=\"campo\" type=\"radio\" value=\"$tabla[0]\"> $tabla[0]<br />\r\n"; }
?>
</p>
<p><input type="submit" name="Submit" value="Crear Formulario" class="boton">
</p><br />
<input type="hidden" name="hacer" value="true">
</label>
</form>
<?php }
else
{
?>
<script language="JavaScript">
/*
By Mike Hall (MHall75819@aol.com)
*/
var NS4 = (document.layers); // Which browser?
var IE4 = (document.all);
var win = window; // window to search.
var n = 0;
function findInPage(str) {
var txt, i, found;
if (str == "")
return false;
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (NS4) {
// Look for match starting at the current point. If not found, rewind
// back to the first match.
if (!win.find(str))
while(win.find(str, false, true))
n++;
else n++;
// If not found in either direction, give message.
if (n == 0)
alert("Not found.");
}
if (IE4) {
txt = win.document.body.createTextRange();
// Find the nth match from the top of the page.
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
}
// Otherwise, start over at the top of the page and find first match.
else {
if (n > 0) {
n = 0;
findInPage(str);
}
// Not found anywhere, give message.
else
alert("Not found.");
}
}
return false;
}
</script>
<?php
// vemos los campos de la tabla elegida
$tabla = $_POST["nombre_tabla"];
if (empty($tabla)) { die("<span class=\"style10\">Error!!! no eligío una tabla </span>"); }
$archivo = basename($_SERVER["PHP_SELF"]);
$sql = sprintf("SHOW FIELDS FROM `%s`", mysql_real_escape_string($tabla));
$query = @mysql_query($sql,$conexion);
// determinamos la cantidad de campos de la tabla
$sql = "select * from $tabla";
$query2 = @mysql_query($sql,$conexion);
$cant_campo = @mysql_num_fields($query2);
print "<div class=\"style3\">La tabla [ <span class=\"style6\">$tabla</span> ] esta conformada por $cant_campo campos</div>";
// determinamos los campos autoincrementales para que no salgan en el formulario
$value = '$'."sql = sprintf(\"INSERT INTO $tabla (";
for ($ciclo=0; $ciclo < $cant_campo; $ciclo++) {
$value .= mysql_field_name($query2, $ciclo).', ';
if (substr_count(mysql_field_flags($query2, $ciclo),"auto_increment"))
{ $campo_auto = mysql_field_name($query2, $ciclo); }
}
$value = substr($value,0,strlen($value)-2).") \r\n\t VALUES ( ";
// hacemos el formulario
$formulario = "<form action=\"$archivo\" method=\"post\" name=\"$tabla\" target=\"_self\">\n\r";
$mysql_r = '';
while ($campo = @mysql_fetch_array($query)) {
$nombre_campo = ucfirst(strtolower($campo[0]));
if ($campo[0] != $campo_auto) {
$formulario.= " <label><b>$nombre_campo:</b>\r<input type=\"text\" name=\"$campo[0]\" /></label><br /> \n\r";
$value .= "'%s', ";
$mysql_r .= " \t mysql_real_escape_string("."$".$campo[0]."), \r\n" ; }
else { $value .= "NULL, "; }
}
$formulario.= " <input type=\"submit\" name=\"Submit\" value=\"Enviar\" />\n\r";
$formulario.= " <input type=\"reset\" name=\"Reset\" value=\"Limpiar\" />\n\r";
$formulario.= "</form>";
print "<p><br /><form NAME=\"Copiar\">
<div align=\"left\"><p><input type=\"button\" value=\"Seleccionar Todo \"
onClick=\"javascript:this.form.valor.focus();this.form.valor.select();\"></p>";
print "<p><textarea name=\"valor\" cols=\"75\" rows=\"20\" class=\"campo\">$formulario</textarea></p></div>";
print "<p><br />
<div class=\"style3\"><label>Sentencia SQL del formulario</label></div>
<div align=\"left\"><p><input type=\"button\" value=\"Seleccionar Todo \"
onClick=\"javascript:this.form.insert.focus();this.form.insert.select();\"></p>";
$value = substr($value,0,strlen($value)-2).")\",\r\n";
$value .= substr($mysql_r,0,strlen($mysql_r)-4).");";
print "<p><textarea name=\"insert\" cols=\"75\" rows=\"8\" class=\"campo\">$value</textarea></p>";
$_POST["hacer"] = '';
print "</form>";
}
?>
</td>
</tr>
<tr>
<td align="right" valign="bottom" class="style4">Versión 0.3
<a href="http://www.php.org.ve" title="PHP de Venezuela" target="_blank" class="style4">PHP de Venezuela</a> </td>
</tr>
<tr>
<td align="right" valign="bottom"><hr></td>
</tr>
</table>
<?php @mysql_close($conexion); ?>
</body>
</html>