image


Valora:  2.5/5
Inicio » PHP » PHP Tutorial » Database access




Inserting records

So far we have connected to and queried a database, now we will show how to insert new records into the database

In order to do this, we will use a form and in the attribute ACTION from FORM <FORM ACTION="programPHP"> we will indicate how the form shall be processed in a PHP page- what this page will do is insert data from the form into the database.


ejem07d.phtml
<!-- PHP Tutorial WebEstilo.com -->
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
<H1>Ejemplo de uso de bases de datos con PHP y MySQL</H1>
<FORM ACTION="procesar.phtml">
<TABLE>
<TR>
   <TD>Nombre:</TD>
   <TD><INPUT TYPE="text" NAME="nombre" SIZE="20" MAXLENGTH="30"></TD>
</TR>
<TR>
   <TD>Apellidos:</TD>
   <TD><INPUT TYPE="text" NAME="apellidos" SIZE="20" MAXLENGTH="30"></TD>
</TR>
</TABLE>
<INPUT TYPE="submit" NAME="accion" VALUE="Grabar">
</FORM>
<hr>
<?php
   include("conex.phtml");
   $link=Conectarse();
   $result=mysql_query("select * from prueba",$link);
?>

   <TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1>
      <TR><TD>&nbsp;<B>Nombre</B></TD> <TD>&nbsp;<B>Apellidos</B>&nbsp;</TD></TR>
<?php      

   while($row = mysql_fetch_array($result)) {
      printf("<tr><td>&nbsp;%s</td> <td>&nbsp;%s&nbsp;</td></tr>", $row["Nombre"], $row["Apellidos"]);
   }
   mysql_free_result($result);
   mysql_close($link);   
?>

</table>
</body>
</html>

Execute View code


procesar.phtml
<?php
   include("conex.phtml");
   $link=Conectarse();
   $nombre=$_GET['nombre'];
   $apellidos=$_GET['apellidos'];   
   mysql_query("insert into prueba (Nombre,Apellidos) values ('$nombre','$apellidos')",$link);
   
   header("Location: ejem07d.phtml");
?>




The first PHP page ejem07d.phtml is a form that allows us to insert name and last name to be added to the database, followed by a query that shows us the content of the test table. The form calls the page procesar.phtml that will add data to the table.

The second page procesar.phtml connects to the database and inserts a new record with the SQL database language statement "insert". Once the record has been inserted, the page ejem07d.phtml is reloaded.






WebEstilo.com - Introduzca su e-mail y conozca las novedades. No hacemos Spam.
Google
  Web WebEstilo.com   
 
Valid HTML 4.01!
Última modificación:25 de Diciembre de 2004. Spain - España.
© 1998-2004 por Joaquin Gracia. Todos los derechos reservados.