Creación de una consulta y una alta con PHP y con cliente JS
consulta.php
<?php
header('Content-Type: application/json; charset=utf-8');
$conn = new mysqli('localhost', 'root', '', 'test');
if ($conn->connect_error) {
echo "Falló la conexión: ".$conn->connect_error;
}
$conn->set_charset('utf8mb4');
$sql = 'SELECT * FROM usuarios';
$result = $conn->query($sql);
$data=array();
while($row=$result->fetch_assoc()){
$data[]=$row;
}
header('Content-Type: application/json');
echo json_encode($data);
$conn->close();
?>
consulta.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>id</th>
<th>nombre</th>
<th>edad</th>
</tr>
</thead>
<tbody id="usuarios-body"></tbody>
</table>
<script>
function cargarUsuarios() {
fetch('./consulta.php')
.then(respuesta => respuesta.json())
.then(usuarios => mostrarUsuarios(usuarios))
.catch(error => console.error(error));
}
function mostrarUsuarios(usuarios) {
const tbody = document.getElementById('usuarios-body');
tbody.innerHTML = '';
usuarios.forEach((usuario) => {
const fila = document.createElement('tr');
const celdaId = document.createElement('td');
celdaId.textContent = usuario.id;
const celdaNombre = document.createElement('td');
celdaNombre.textContent = usuario.nombre;
const celdaEdad = document.createElement('td');
celdaEdad.textContent = usuario.edad;
fila.appendChild(celdaId);
fila.appendChild(celdaNombre);
fila.appendChild(celdaEdad);
tbody.appendChild(fila);
});
}
cargarUsuarios();
</script>
</body>
</html>
alta.php
<?php
header('Content-Type: application/json; charset=utf-8');
$conn = new mysqli('localhost', 'root', '', 'test');
if ($conn->connect_error) {
echo "Falló la conexión";
exit;
}
$conn->set_charset('utf8mb4');
$nombre = $_POST['nombre'];
$edad = $_POST['edad'];
$edad = (int) $edad;
$stmt = $conn->prepare('INSERT INTO usuarios (nombre, edad) VALUES (?, ?)');
$stmt->bind_param('si', $nombre, $edad);
if (!$stmt->execute()) {
echo "Error al insertar";
}else {
echo "Registro insertado";
}
$stmt->close();
$conn->close();
?>
alta.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alta</title>
</head>
<body>
<label>nombre
<input type="text" id="nombre">
</label>
<label>edad
<input type="text" id="edad">
</label>
<button onclick="alta()">Alta</button>
<script>
function alta() {
const nombre = document.getElementById("nombre").value;
const edad = document.getElementById("edad").value;
fetch('./alta.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: `nombre=${encodeURIComponent(nombre)}&edad=${encodeURIComponent(edad)}`
})
.then(respuesta => respuesta.text())
.then(mensaje => console.log(mensaje))
.catch(error => console.error(error));
}
</script>
</body>
</html>
