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;
}
?>
<!-- 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> Nombre</TD><TD> Apellidos </TD></TR>
<?php
while($row = mysql_fetch_array($result)) {
printf("<tr><td> %s</td><td> %s </td></tr>", $row["Nombre"],$row["Apellidos"]);
}
mysql_free_result($result);
mysql_close($link);
?>
</table>
</body>
</html>
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.