VeneHosting.com :: Tu Hosting en Venezuela

Autor Tema: Creación de Formularios Dinámicos de Una base de datos  (Leído 611 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado xombra

  • Moderador Global
  • Usuario Dedicado
  • *****
  • Mensajes: 169
  • Puntuación: 3
  • Sexo: Masculino
    • Ver Perfil
    • http://www.xombra.com
Creación de Formularios Dinámicos de Una base de datos
« : 28 de abril de 2008, 02:31:19 pm »
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
Código: [Seleccionar]
; 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
Código: [Seleccionar]
<?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()) {
      $valorstripslashes($valor);  }
 return 
$valor;
}

function 
filter($string) {
  $replace "%20";
  $search = array(">""<""|"";""-","&#39;","&");
  $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
Código: [Seleccionar]
<!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 &#39;conexion.php&#39;;
?>

<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&oacute;n de Formularios Din&aacute;micos </td>
  </tr>
  <tr>
    <td height="35" align="left" valign="middle" class="style3">
<?php 
  if (empty($_POST[&#39;hacer&#39;])) { ?>

<p>Indique la TABLA MySql a la cual se le crear&aacute; 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[&#39;hacer&#39;])) { ?>


      <form action="<?php print $_SERVER[&#39;PHP_SELF&#39;]; ?>" 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&iacute;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 = &#39;$&#39;."sql = sprintf(\"INSERT INTO $tabla (";
for ($ciclo=0$ciclo $cant_campo$ciclo++) {
    $value .=  mysql_field_name($query2$ciclo).&#39;, &#39;;
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 = &#39;&#39;;
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 .= "&#39;%s&#39;, ";  
 $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"] = &#39;&#39;; 
print "</form>";




       }
       

?>

    </td>
  </tr>
  <tr>
    <td align="right" valign="bottom" class="style4">Versi&oacute;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>
« Última Modificación: 28 de agosto de 2008, 10:59:12 am por xombra »
---------------------------------------------
Sitio web: http://www.xombra.com
Coordinador Safecreative Venezuela - http://www.safecreative.org
Coordinador Regional AWVEN - http://www.awven.com
Twitter: @xombra
Identi.ca: xombra
GNU/Linux User: #414452
-------------------------------------

Desconectado Angeloz

  • Novato
  • *
  • Mensajes: 1
  • Puntuación: 0
  • Sexo: Masculino
  • Ayuda en PHP
    • Ver Perfil
    • • [ ZeRo ] •
Tengo un problema :(!!
« Respuesta #1 : 25 de junio de 2008, 10:59:09 am »
Hola Aqui dejo mi codigo PHP!! Si funciona!! Solo que Cuando envia el formulario solo va a la base de datos, alguien que me ayude a editarlo para que envie se envie a la Base de datos y luego a mi mail... Agradeceria mucho su ayuda :)

<?php

$opt=$HTTP_GET_VARS["opt"];

if ($opt==1)
{
 $nombre=$HTTP_GET_VARS["nombre"];
 $email=$HTTP_GET_VARS["email"];
 $web=$HTTP_GET_VARS["web"];
 $pais=$HTTP_GET_VARS["pais"];
 $mensaje=$HTTP_GET_VARS["mensaje"];

 $sql="insert into prospectos (nombre, email, web, pais, mensaje) values ('".$nombre."','".$email."','".$web."','".$pais."','".$mensaje."')";
 $res=mysql_query($sql,$bd) or die (mysql_error());
}

?>


<html>
<head>
<title>Nombre</title>
<style type="text/css">
body {
   scrollbar-3dlight-color: #111111;
   scrollbar-arrow-color: #444444;
   scrollbar-darkshadow-color: #111111;
   scrollbar-face-color: #000000;
   scrollbar-highlight-color: #000000;
   scrollbar-shadow-color: #000000;
   scrollbar-track-color: #111111;
}
</style>
</head>

<script language="javascript">

function verifica()
{
 if (f.email.value=="")
  {
   alert ("Por favor ingrese su email");
   return;
  }

 f.opt.value=1;
 f.submit();
}

</script>

<body>

<form name="f">
<input type="hidden" name="opt">
<div align="center">
<center>
<table border="0" cellpadding="2" cellspacing="2" width="290" background="http://i281.photobucket.com/albums/kk215/zero2x/Zerito/0000_04.jpg">
    <tr align="center">
      <td><font color="#808080"><b>Nick :</b></font></td>
    </tr>
    <tr align="center">
      <td><input type="text" name="nombre" size="30" style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></td>
    </tr>
    <tr align="center">
      <td><font color="#808080"><b>Email :</b></font></td>
   </tr>
   <tr align="center">
      <td><input type="text" name="email" size="30" style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></td>
    </tr>
   <tr align="center">
      <td><font color="#808080"><b>Web :</b></font></td>
   </tr>
   <tr align="center">
      <td><input type="text" name="web" size="30" style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></td>
    </tr>
   <tr align="center">
      <td><font color="#808080"><b>Pais :</b></font></td>
   </tr>
   <tr align="center">
      <td><input type="text" name="pais" size="30" style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></td>
    </tr>
   <tr align="center">
      <td colspan="2"><font color="#808080"><b>Mensaje :</b></font></td>
    </tr>
    <tr align="center">
      <td colspan="2"><textarea rows="8" name="mensaje" cols="30" style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></textarea></td>
    </tr>
    <tr align="center">
      <td colspan="2">
        <p align="center"><input type="button" value="Enviar!" name="B3" onclick=verifica() style="background: #000000; font: bold 13px Tahoma; color: #808080; border: #D2600E 2px ridge;"></td>
    </tr>
  </table>
  </center>
</div>
</form>

</body>
</html>
• [ Angeloz ★ ] •

Desconectado Nathan

  • Novato
  • *
  • Mensajes: 15
  • Puntuación: 0
  • Sexo: Masculino
  • "Coder = Artist"
    • Ver Perfil
Re: Creación de Formularios Dinámicos de Una base de datos
« Respuesta #2 : 08 de julio de 2008, 03:51:15 pm »
Saludos Angeloz....

Primero que todo, bueno el scrip de Xombra... lo usare con algunas implementaciones...

Respecto a lo que necesitas pues prueba lo siguiente:

En tu codigo de proceso del formulario agrega lo siguiente para que envie el correo usando la funcion mail() de php:

Código: [Seleccionar]
// recibes las variables que pasaras por correo y la almacenas en una nueva...

    $msg = "Formulario enviado a\n";
    $msg .= "Nombre: " . $nombre . "\n";
    $msg .= "Email: " . $email . "\n";
    $msg .= "Pais: " . $pais . "\n";
    $msg .= "Mensaje: " . $mensaje . "\n";

// colocas el correo donde enviaras tu contenido, y armas la funcion con tus datos

    mail("tucorreo@tudominio.com","Formulario recibido",$msg);

// muestras una respuesta o redireccionas a una nueva pagina

    echo "El formulario se ha enviado correctamente.";

// o redireccionas a una nueva pagina

    header( 'Location: http://www.tudominio.com/tu_index.php' ) ;


Espero te sirva :)
"Cada uno de nosotros es Dios, cada uno de nosotros lo sabe todo. Solo necesitamos abrir nuestras mentes para escuchar nuestra propia sabiduría"

 - BUDA -

PHP de Venezuela

Re: Creación de Formularios Dinámicos de Una base de datos
« Respuesta #2 : 08 de julio de 2008, 03:51:15 pm »

 

PHP de Venezuela on Facebook