INSERT UPLOAD JSON FETCH PUT POST GET DELETE FOTOS MYSQL PHP PDO JSON API AJAX EXPORT VANILLA
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label for="name">Image Name:</label>
<input type="text" name="name" id="name">
<br>
<label for="description">Description:</label>
<textarea name="description" id="description"></textarea>
<br>
<label for="image">Image File:</label>
<input type="file" name="image" id="image">
<br>
<input type="submit" value="Upload">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Validate input data
$name = $_POST['name'];
$description = $_POST['description'];
$image = $_FILES['image'];
if (empty($name) || empty($image)) {
die('Image name and file are required');
}
// Move uploaded file to permanent location
$target_dir = 'uploads/';
$target_file = $target_dir . basename($image['name']);
move_uploaded_file($image['tmp_name'], $target_file);
// Insert record into database
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->prepare('INSERT INTO images (name, description, image_file) VALUES (?, ?, ?)');
$stmt->execute([$name, $description, $target_file]);
header('Location: index.php');
}
<?php
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->query('SELECT * FROM images');
foreach ($stmt as $row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['description'] . '</td>';
echo '<td><img src="' . $row['image_file'] . '"></td>';
echo '<td><a href="edit.php?id=' . $row['id'] . '">Edit</a> | <a href="delete.php?id=' . $row['id'] . '">Delete</a></td>';
echo '</tr>';
}
<!DOCTYPE html>
<html>
<head>
<title>Fetch data from MySQL using JavaScript and PHP</title>
</head>
<body>
<table id="table"></table>
<script>
fetch('api.php')
.then(response => response.json())
.then(data => {
let table = document.getElementById('table');
let tr = document.createElement('tr');
let th1 = document.createElement('th');
let th2 = document.createElement('th');
let th3 = document.createElement('th');
let th4 = document.createElement('th');
th1.innerHTML = 'ID';
th2.innerHTML = 'Name';
th3.innerHTML = 'Email';
th4.innerHTML = 'Phone';
tr.appendChild(th1);
tr.appendChild(th2);
tr.appendChild(th3);
tr.appendChild(th4);
table.appendChild(tr);
data.forEach(user => {
let tr = document.createElement('tr');
let td1 = document.createElement('td');
let td2 = document.createElement('td');
let td3 = document.createElement('td');
let td4 = document.createElement('td');
td1.innerHTML = user.id;
td2.innerHTML = user.name;
td3.innerHTML = user.email;
td4.innerHTML = user.phone;
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
table.appendChild(tr);
});
})
.catch(error => console.log(error));
</script>
</body>
</html>
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';
$dsn = "mysql:host=$host;dbname=$dbname";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$conn = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
echo $e->getMessage();
}
$stmt = $conn->prepare('SELECT * FROM users');
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);
?>
Para realizar una búsqueda en una tabla MySQL y mostrar los resultados en una tabla HTML usando JavaScript y PHP, se puede utilizar la función fetch de JavaScript para enviar una solicitud POST a un archivo PHP que realiza la consulta a la base de datos y devuelve los resultados como un objeto JSON. Luego, se puede utilizar JavaScript para construir la tabla HTML y mostrar los resultados en ella.
Aquí hay un ejemplo de código que muestra cómo hacer esto:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Búsqueda de datos</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Búsqueda de datos</h1>
<form>
<label for="search">Buscar:</label>
<input type="text" id="search">
<button type="button" id="btn-search">Buscar</button>
</form>
<table id="results">
<thead>
<tr>
<th>Id</th>
<th>Nombre</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
// función que construye la tabla HTML con los resultados de la búsqueda
function buildTable(data) {
const tbody = document.querySelector('#results tbody');
tbody.innerHTML = '';
for (let i = 0; i < data.length; i++) {
const row = `
<tr>
<td>${data[i].id}</td>
<td>${data[i].name}</td>
<td>${data[i].email}</td>
</tr>
`;
tbody.insertAdjacentHTML('beforeend', row);
}
}
// evento del botón de búsqueda
document.querySelector('#btn-search').addEventListener('click', () => {
const searchValue = document.querySelector('#search').value.trim();
if (searchValue !== '') {
// enviar solicitud POST a search.php con el valor de búsqueda
fetch('search.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ search: searchValue })
})
.then(response => response.json())
.then(data => {
buildTable(data);
})
.catch(error => console.error(error));
}
});
</script>
</body>
</html>
<?php
// conexión a la base de datos
$host = 'localhost';
$dbname = 'database_name';
$username = 'database_username';
$password = 'database_password';
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
die('Error de conexión a la base de datos: ' . $e->getMessage());
}
// obtener el valor de búsqueda enviado desde el formulario
$search = $_POST['search'];
// construir la consulta SQL con la cláusula LIKE para buscar en la tabla
$sql = "SELECT * FROM users WHERE name LIKE :search OR email LIKE :search";
$stmt = $pdo->prepare($sql);
$stmt->execute(['search' => '%' . $search . '%']);
// obtener los resultados de la consulta
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// devolver los resultados como objeto JSON
header('Content-Type: application/json');
echo json_encode($results);
?>
Para hacer un CRUD (Create, Read, Update, Delete) con JavaScript, MySQL y PHP, y usando la API Fetch, se pueden seguir los siguientes pasos:
Crear una base de datos en MySQL con una tabla que tenga los campos necesarios para almacenar la información a manejar en el CRUD.
Crear un archivo PHP que maneje las peticiones HTTP para realizar las operaciones del CRUD. En este archivo se deben implementar las funciones para conectarse a la base de datos, recibir y procesar los datos enviados desde JavaScript mediante la API Fetch, y enviar las respuestas correspondientes. Este archivo debe manejar las siguientes peticiones:
GET: Para obtener los registros de la base de datos.
POST: Para agregar nuevos registros a la base de datos.
PUT: Para actualizar registros existentes en la base de datos.
DELETE: Para eliminar registros de la base de datos.
Crear un archivo JavaScript que implemente la lógica de la aplicación y maneje las interacciones con el usuario. En este archivo se deben crear las funciones que envíen las peticiones HTTP mediante la API Fetch, y actualizar la interfaz de usuario en respuesta a las respuestas recibidas. Se debe crear una función para cada una de las operaciones del CRUD (crear, leer, actualizar y eliminar).
Crear la interfaz de usuario con HTML y CSS, usando elementos HTML como <table>, <button> y <input>. Se deben asignar identificadores y clases a los elementos necesarios para poder manipularlos con JavaScript.
A continuación, se presenta un ejemplo de código que implementa un CRUD con Fetch, MySQL y PHP, para una tabla de empleados:
Aquí te dejo un ejemplo de cómo actualizar datos en MySQL utilizando una API PHP y Fetch API en JavaScript con un formulario:
En tu archivo HTML, crea un formulario con los campos que deseas actualizar. En este ejemplo, utilizaremos un campo para ingresar el ID del registro a actualizar y dos campos para ingresar los nuevos valores de los campos 'nombre' y 'edad':
<form id="form-update">
<label for="id">ID:</label>
<input type="text" id="id" name="id"><br>
<label for="nombre">Nuevo nombre:</label>
<input type="text" id="nombre" name="nombre"><br>
<label for="edad">Nueva edad:</label>
<input type="text" id="edad" name="edad"><br>
<button type="submit">Actualizar</button>
</form>
2. Crea un archivo PHP que reciba los datos del formulario y actualice el registro en la base de datos. En este ejemplo, el archivo se llama 'update.php':
<?php
// Conectamos a la base de datos
$pdo = new PDO('mysql:host=localhost;dbname=nombre_de_la_base_de_datos', 'nombre_de_usuario', 'contraseña');
// Preparamos la consulta SQL para actualizar el registro
$stmt = $pdo->prepare('UPDATE tabla SET nombre = :nombre, edad = :edad WHERE id = :id');
// Obtenemos los datos enviados por el formulario
$id = $_POST['id'];
$nombre = $_POST['nombre'];
$edad = $_POST['edad'];
// Asignamos los valores a los parámetros de la consulta preparada
$stmt->bindParam(':id', $id);
$stmt->bindParam(':nombre', $nombre);
$stmt->bindParam(':edad', $edad);
// Ejecutamos la consulta
if ($stmt->execute()) {
// Si la consulta se ejecuta correctamente, devolvemos un mensaje de éxito
echo json_encode(['mensaje' => 'Registro actualizado correctamente']);
} else {
// Si hay un error, devolvemos un mensaje de error
echo json_encode(['mensaje' => 'Error al actualizar el registro']);
}
n tu archivo JavaScript, crea una función que envíe los datos del formulario al archivo PHP utilizando Fetch API. En este ejemplo, la función se llama 'actualizarRegistro':
function actualizarRegistro() {
// Obtenemos los valores del formulario
const id = document.getElementById('id').value;
const nombre = document.getElementById('nombre').value;
const edad = document.getElementById('edad').value;
// Enviamos los datos al archivo PHP utilizando Fetch API
fetch('update.php', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({id, nombre, edad})
})
.then(response => response.json())
.then(data => {
// Si la respuesta es exitosa, mostramos un mensaje de éxito
alert(data.mensaje);
})
.catch(error => {
// Si hay un error, mostramos un mensaje de error
alert('Error al actualizar el registro');
});
}
To export a MySQL table to JSON format using PHP, you can follow these steps:
1. Connect to the MySQL database using PHP's mysqli or PDO extension.
2. Execute a SELECT query to retrieve the data from the table.
3. Fetch the results of the query and store them in an array.
4. Convert the array to JSON using PHP's json_encode() function.
Here's an example PHP code that exports a MySQL table named my_table to a JSON file named my_table.json:
<?php
// Connect to the MySQL database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute a SELECT query
$sql = "SELECT * FROM my_table";
$result = $conn->query($sql);
// Fetch the results and store them in an array
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// Convert the array to JSON
$json = json_encode($rows);
// Save the JSON to a file
file_put_contents('my_table.json', $json);
?>
<?php
// Connect to the MySQL database using PDO
$dsn = 'mysql:dbname=your_database;host=localhost;charset=utf8';
$username = 'your_username';
$password = 'your_password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Execute a SELECT query
$sql = "SELECT * FROM my_table";
$stmt = $pdo->query($sql);
// Fetch the results and store them in an array
$rows = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
// Convert the array to JSON
$json = json_encode($rows);
// Save the JSON to a file
file_put_contents('my_table.json', $json);
?>
To export a MySQL table to .sql format using PHP's PDO extension, you can follow these steps:
1. Connect to the MySQL database using PDO with a DSN string that specifies the database name, host, and charset.
2. Execute a SELECT query to retrieve the data from the table.
3. Fetch the results of the query and store them in an array.
4. Generate the SQL statements to create the table and insert the data into it.
5. Save the SQL statements to a .sql file.
Here's an example PHP code that exports a MySQL table named my_table to a .sql file named my_table.sql using PDO:
<?php
// Connect to the MySQL database using PDO
$dsn = 'mysql:dbname=your_database;host=localhost;charset=utf8';
$username = 'your_username';
$password = 'your_password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Execute a SELECT query
$sql = "SELECT * FROM my_table";
$stmt = $pdo->query($sql);
// Fetch the results and store them in an array
$rows = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
// Generate the SQL statements to create the table and insert the data into it
$table_name = 'my_table';
$columns = array_keys($rows[0]);
$column_names = implode(', ', $columns);
$column_values = array();
foreach ($rows as $row) {
$values = array();
foreach ($row as $value) {
$values[] = $pdo->quote($value);
}
$column_values[] = '(' . implode(', ', $values) . ')';
}
$insert_values = implode(",\n", $column_values);
$sql = "DROP TABLE IF EXISTS $table_name;\n";
$sql .= "CREATE TABLE $table_name ($column_names);\n";
$sql .= "INSERT INTO $table_name ($column_names) VALUES\n$insert_values;\n";
// Save the SQL statements to a .sql file
file_put_contents('my_table.sql', $sql);
?>
This code retrieves all the rows from the my_table table and generates the SQL statements to create the table and insert the data into it. The resulting SQL statements are then saved to a file named my_table.sql using the file_put_contents() function. You can modify this code to export a different table or to save the SQL statements to a different filename.
To export the full database to .sql format using PHP's PDO extension, you can follow these steps:
Connect to the MySQL database using PDO with a DSN string that specifies the database name, host, and charset.
Execute a SHOW TABLES query to retrieve the list of tables in the database.
Loop through the tables and generate the SQL statements to create the table and insert the data into it.
Concatenate all the SQL statements into a single string.
Save the SQL statements to a .sql file.
<?php
// Connect to the MySQL database using PDO
$dsn = 'mysql:dbname=your_database;host=localhost;charset=utf8';
$username = 'your_username';
$password = 'your_password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Execute a SHOW TABLES query
$sql = "SHOW TABLES";
$stmt = $pdo->query($sql);
// Loop through the tables and generate the SQL statements to create the table and insert the data into it
$sql = '';
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$table_name = $row[0];
// Generate the SQL statements to create the table and insert the data into it
$stmt2 = $pdo->query("SELECT * FROM $table_name");
$rows = array();
while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row2;
}
$columns = array_keys($rows[0]);
$column_names = implode(', ', $columns);
$column_values = array();
foreach ($rows as $row) {
$values = array();
foreach ($row as $value) {
$values[] = $pdo->quote($value);
}
$column_values[] = '(' . implode(', ', $values) . ')';
}
$insert_values = implode(",\n", $column_values);
$sql .= "DROP TABLE IF EXISTS $table_name;\n";
$sql .= "CREATE TABLE $table_name ($column_names);\n";
$sql .= "INSERT INTO $table_name ($column_names) VALUES\n$insert_values;\n";
}
// Save the SQL statements to a .sql file
file_put_contents('my_database.sql', $sql);
?>
This code retrieves the list of tables in the database and generates the SQL statements to create the table and insert the data into it for each table. The resulting SQL statements are then concatenated into a single string and saved to a file named my_database.sql using the file_put_contents() function. You can modify this code to export a different database or to save the SQL statements to a different filename.
<?php
// Create a DSN for the Microsoft Access database using the ODBC Data Source Administrator
$dsn = 'odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\path\\to\\database.mdb;Uid=your_username;Pwd=your_password;';
// Connect to the Microsoft Access database using PDO
$username = 'your_username';
$password = 'your_password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Execute a SELECT query to retrieve the data from the table
$sql = "SELECT * FROM Customers";
$stmt = $pdo->query($sql);
// Build an HTML table to display the data
echo "<table>";
echo "<tr><th>Customer ID</th><th>Customer Name</th><th>Customer Address</th></tr>";
// Loop through the result set and populate the HTML table with the data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['CustomerID'] . "</td>";
echo "<td>" . $row['CustomerName'] . "</td>";
echo "<td>" . $row['CustomerAddress'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
ajax post jquery json api search mysql pdo php display table html
<?php
// Connect to the MySQL database using PDO
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Retrieve the search query from the AJAX request
$search = $_POST['search'];
// Build a SELECT query that filters the data based on the search query
$sql = "SELECT * FROM products WHERE name LIKE :search OR description LIKE :search OR price LIKE :search";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
$stmt->execute();
// Fetch the data from the result set and store it in an array of arrays
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array_values($row);
}
// Convert the data to JSON format and send it back to the client
header('Content-Type: application/json');
echo json_encode($data);
?>
<form id="search-form">
<label for="search">Search:</label>
<input type="text" id="search" name="search">
<button type="submit">Submit</button>
</form>
<table id="results-table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Add an event listener to the form that sends an AJAX request when the form is submitted
$('#search-form').submit(function(event) {
event.preventDefault();
var search = $('#search').val();
$.ajax({
url: 'search.php',
type: 'POST',
dataType: 'json',
data: {
search: search
},
success: function(data) {
// Use jQuery methods to create an HTML table from the search results and display it in the HTML document
$('#results-table tbody').empty();
$.each(data, function(index, row) {
var rowHtml = '<tr>';
$.each(row, function(index, value) {
rowHtml += '<td>' + value + '</td>';
});
rowHtml += '</tr>';
$('#results-table tbody').append(rowHtml);
});
}
});
});
</script>
Comentarios
Publicar un comentario