PHP para bases de datos MySQL
Se va a necesitar la siguiente tabla de MySQL:
CREATE TABLE tablacurso (
id tinyint(3) unsigned NOT NULL auto_increment,
nombre varchar(30) DEFAULT '0' ,
direccion varchar(30) DEFAULT '0' ,
telefono varchar(30) DEFAULT '0' ,
email varchar(30) DEFAULT '0' ,
imagen varchar(30) DEFAULT '0' ,
PRIMARY KEY (id)
);
Conectarse
Empecemos con el primer script, que nos mostrará como conectarnos a un base de datos (conectarse.php).
conectarse.php
<html>
<head>
<title>Ejemplo de PHP</title>
</head>
<body>
<?php
function Conectarse(){
if (!($link=mysql_connect("localhost","usuario","password"))){
echo "Error conectando a la base
de datos.";
exit();
}
if (!mysql_select_db("basecurso",$link)){
echo "Error seleccionando la base
de datos.";
exit();
}
return $link;
}
Conectarse();
echo "Conexión con la base de datos
conseguida.<br>";
?>
</body>
</html>
Como podemos ver en el ejemplo anterior aislé lo necesario para la conexión en una función, ahora esa función la pondremos en un archivo PHP solo (conec.php).
<?php
function Conectarse(){
if (!($link=mysql_connect("localhost","usuario","password"))) {
exit();
}
if (!mysql_select_db("basecurso",$link)){
exit();
}
return $link;
}
?>
Ya que tenemos la función en un archivo separado solo hay que mandarlo llamar cuando sea necesario, de esta forma cuando tengamos aplicaciones complejas que use muchas páginas php y sea necesario cambiarle algo a la conexión solo se le tenga que hacer el cambio a este pequeño archivo y no a todas las páginas.
Agregar registros
Veremos un ejemplo de agregar registros a la base de datos (insertareg.php y agregar.php).
<html>
<head>
<title>Ejemplo
de PHP</title>
</head>
<body>
<h1>Ejemplo de uso de bases de
datos con PHP y MySQL</h1>
<form action="agregar.php"
method="post">
<TABLE>
<tr>
<td>Nombre:</td>
<td><input type="text" name="nombre" size="20" maxlength="30"></td>
</tr>
<tr>
<td>Direccion:</td>
<td><input type="text" name="direccion"
size="20" maxlength="30"></td>
</tr>
<tr>
<td>Telefono:</td>
<td><input type="text" name="telefono"
size="20" maxlength="30"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" size="20" maxlength="30"></td>
</tr>
<tr>
<td>Imagen:</td>
<td><input type="text" name="imagen" size="20" maxlength="30"></td>
</tr>
</TABLE>
<input type="submit"
name="accion" value="Grabar">
</FORM>
<hr>
<?php
include("conec.php");
$link=Conectarse();
$result=mysql_query("select
* from tablacurso",$link);
?>
<table border="1" cellspacing="1" cellpadding="1">
<tr>
<td> Nombre</td>
<td> Dirección </td>
<td> Telefono </td>
<td> Email </td>
<td> Imagen </td>
</tr>
<?php
while($row = mysql_fetch_array($result)) {
printf("<tr><td> %s </td><td> %s
</td><td> %s </td><td> %s
</td><td> <imgsrc=%s> </td></tr>",
$row["nombre"], $row["direccion"], $row["telefono"],
$row["email"], $row["imagen"]);
}
mysql_free_result($result);
?>
</table>
</body>
</html>
agregar.php
<?php
include("conec.php");
$link=Conectarse();
$Sql="insert
into tablacurso (nombre,direccion,telefono,email,imagen) values ('".$_POST["nombre"]."','".$_POST["direccion"]."',
'".$_POST["telefono"]."', '".$_POST["email"]."',
'".$_POST["imagen"]."')";
mysql_query($Sql,$link);
header("Location:
insertareg.php");
?>
Modificar registros
Veremos un ejemplo de modificar registros a la base de datos, consta de tres archivos diferentes, el primero para introducir la consulta por el campo nombre, el segundo para realizar los cambios necesarios y el tercero para modificar la base de datos (consulta.htm, busca.php y modifica.php).
<html>
<head>
<title>Ejemplo
de PHP</title>
</head>
<body>
<h1>Ejemplo de modificar</h1>
<form action="busca.php"
method="post">
Nombre:
<input type="text"
name="nombre" size="20" maxlength="30">
<input type="submit"
name="accion" value="Buscar">
</FORM>
</body>
</html>
busca.php
<html>
<body>
<?php
include("conec.php");
$link=Conectarse();
$Sql="select * from tablacurso where nombre like '%."$_POST["nombre"]."%'";
$result=mysql_query($Sql,$link);
?>
<table border="1" cellspacing="1" cellpadding="1">
<tr>
<td> Nombre</td>
<td> Dirección </td>
<td> Telefono </td>
<td> Email </td>
<td> Imagen </td>
</tr>
<form name="form1"
method="post" action="modifica.php">
<?php
while($row =
mysql_fetch_array($result))
{
printf("<tr><td><INPUT
TYPE='text' NAME='nombre' SIZE='20' MAXLENGTH='30' value='%s'></td><td> <INPUT
TYPE='text' NAME='direccion' SIZE='20' MAXLENGTH='30' value='%s'> </td><td> <INPUT
TYPE='text' NAME='telefono' SIZE='20' MAXLENGTH='30' value='%s'> </td><td> <INPUT
TYPE='text' NAME='email' SIZE='20' MAXLENGTH='30' value='%s'> </td><td> <INPUT
TYPE='text' NAME='imagen' SIZE='20' MAXLENGTH='30' value='%s'> </td></tr>",
$row["nombre"],$row["direccion"],$row["telefono"],$row["email"],$row["imagen"]);
}
mysql_free_result($result);
?>
<input type="submit" name="accion" value="Guardar">
</form>
</body>
</html>
modifica.php
<?php
include("conec.php");
$link=Conectarse();
$Sql="UPDATE tablacurso SET nombre='".$_POST["nombre"]."',
direccion='".$_POST["direccion"]."', email='".$_POST["email"]."',
telefono='".$_POST["telefono"]."' imagen='".$_POST["imagen"]."'
WHERE nombre='".$_POST["nombre"]."'";
mysql_query($Sql,$link);
header("Location:
consulta.htm");
?>
Eliminar registros
Pasemos a la eliminación de registros, este consta de dos archivos, los dos .php el primero es para elegir el registros a borrar y el segundo lo borra (eliminareg.php y borra.php).
<html>
<head>
<title>Ejemplo
de PHP</title>
</head>
<body>
<h1>Ejemplo de uso de bases de
datos con PHP y MySQL</h1>
<?php
include("conec.php");
$link=Conectarse();
$result=mysql_query("select
* from tablacurso",$link);
?>
<table border="1" cellspacing="1" cellpadding="1">
<tr>
<td> Nombre</td>
<td> Dirección </td>
<td> Telefono </td>
<td> Email </td>
<td> Imagen </td>
<td> Borra </td>
</tr>
<?php
while($row =
mysql_fetch_array($result)) {
printf("<tr><td>
%s </td><td> %s </td><td>
%s </td><td> %s </td><td>
%s </td></td><td> <a href=\"borra.php?id=%d\">
Borra </a></td></tr>", $row["nombre"], $row["direccion"],
$row["telefono"], $row["email"], $row["imagen"],
$row["ID"]);
}
mysql_free_result($result);
?>
</table>
</body>
</html>
borra.php
<?php
include("conec.php");
$link=Conectarse();
mysql_query("delete
from tablacurso where ID = ".$_GET["id"],$link);
header("Location:
eliminareg.php");
?>
Ya conocemos como manejar una base de datos de MySQL con PHP, pero que pasa si nosotros tenemos nuestra base de datos en Microsoft Access y es una base de datos enorme, que nos llevaría mucho tiempo en convertirla en MySQL, existe una solución para poder usarla en PHP, esta opción es ODBC.