Ejemplo de base de datos MySQL y AJAX en PHP

AJAX can be used for interactive communication with databases.

AJAX Database Example

In the following AJAX example, we will demonstrate how a web page uses AJAX technology to read information from a MySQL database.

Select a customer from the drop-down list


Customer information will be listed here.

This application consists of four elements:

  • MySQL Database
  • A simple HTML form
  • JavaScript
  • PHP Page

Database

The database used in this example looks something like this:

id CustomerID CompanyName ContactName Address City PostalCode Country
1 Alibaba Alibaba Group Ma Yun ...... Hangzhou 310002 China
2 APPLE Apple Inc. Tim Cook ...... Cupertino 95014 USA
3 BAIDU BAIDU Inc. Li YanHong ...... Beijing 100080 China
4 Canon Canon USA Inc. Tsuneji Uchida ...... New York 11042 USA

Explicación del ejemplo

En el ejemplo anterior, cuando el usuario selecciona un cliente en la lista desplegable superior, se ejecuta la función llamada "showUser()".

Esta función se dispara por el evento onchange.

Este es el código HTML:

Ejemplo

<!doctype html>
<html>
<head>
<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  if (window.XMLHttpRequest) {
    // código para IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // código para IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","/demo/getcustomer.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Por favor, seleccione un cliente:</option>
<option value="1">Alibaba</option>
<option value="2">APPLE</option>
<option value="3">BAIDU</option>
<option value="4">Canon</option>
<option value="5">Google</option>
<option value="6">HUAWEI</option>
<option value="7">Microsoft</option>
<option value="8">Nokia</option>
<option value="9">SONY</option>
<option value="10">Tencent</option>
</select>
</form>
<br>
<div id="txtHint"><b>La información del cliente se listará aquí.</b></div>
</body>
</html>

Ejemplo de ejecución

Explicación del código:

Primero, verifique si se seleccionó un cliente. Si no se seleccionó ningún cliente (str == ""), limpie el contenido de txtHint y salga de la función. Si se seleccionó algún cliente, realice lo siguiente:

  • Crear un objeto XMLHttpRequest
  • Crear una función que se ejecutará cuando el servidor esté listo para responder
  • Enviar la solicitud al archivo en el servidor
  • Por favor, note que el parámetro (q) se agrega a la URL (con contenido de lista desplegable)

Archivo PHP

La página en el servidor llamada "getuser.php" es un archivo PHP.

El código fuente en "getuser.php" realiza consultas a la base de datos MySQL y muestra los resultados en una tabla HTML:

<?php
$q = intval($_GET['q']);
$con = mysqli_connect('MyServer','MyUser','MyPassword','Customers');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM customerslist WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr><th>CustomerID</th><td>" . $row['CustomerID'] . "</td></tr>";
    echo "<tr><th>CompanyName</th><td>" . $row['CompanyName'] . "</td></tr>";
    echo "<tr><th>ContactName</th><td>" . $row['ContactName'] . "</td></tr>";
    echo "<tr><th>Address</th><td>" . $row['Address'] . "</td></tr>";
    echo "<tr><th>City</th><td>" . $row['City'] . "</td></tr>";
    echo "<tr><th>PostalCode</th><td>" . $row['PostalCode'] . "</td></tr>";
    echo "<tr><th>Country</th><td>" . $row['Country'] . "</td></tr>";
}
echo "</table>";
mysqli_close($con);
?>

Explicación: Cuando una consulta se envía desde JavaScript a un archivo PHP, ocurre lo siguiente:

  • PHP abre la conexión con el servidor MySQL
  • Encontramos al cliente correcto
  • Cree una tabla HTML, llene los datos y envíe de vuelta el marcador de posición "txtHint"