image


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




Querying the database

Once we are connected to the database server, we are able to query the database tables.

In order to facilitate programming, we have separated the connection function in a different library, so it can be included in all the pages with database access.

conex.phtml
<!-- PHP Tutorial WebEstilo.com -->
<?php
function Conectarse()
{
   if (!($link=mysql_connect("localhost","usuario","Password")))
   {
      echo "Error conectando a la base de datos.";
      exit();
   }
   if (!mysql_select_db("base_datos",$link))
   {
      echo "Error seleccionando la base de datos.";
      exit();
   }
   return $link;
}
?>

View code


<!-- 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>
<?php
   include("conex.phtml");
   $link=Conectarse();
   $result=mysql_query("select * from prueba",$link);
?>

   <TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1>
      <TR><TD>&nbsp;Nombre</TD><TD>&nbsp;Apellidos&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

In this example we have used 3 new statements: mysql_query, mysql_fetch_array and mysql_free_result. With the mysql_query statement we query the database using the query language SQL, with the statement mysql_fetch_array we extract data from the query to an array, and with the statement mysql_free_result we release the memory used in the query.






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.