☜
☞
MySQL
To create a JavaScript CRUD (Create, Read, Update, Delete) application with a MySQL database, you can use Node.js along with Express for the server-side, and any frontend framework or plain JavaScript for the client-side. Here’s a basic outline of the steps involved:
Backend: Node.js with Express and MySQL
Set up the project:
mkdir crud-app
cd crud-app
npm init -y
npm install express mysql body-parser cors
Create the server (server.js):
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'crud_db'
});
db.connect(err => {
if (err) {
console.error('Database connection failed:', err);
} else {
console.log('Database connected.');
}
});
// Create
app.post('/create', (req, res) => {
const { name, email } = req.body;
const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
db.query(sql, [name, email], (err, result) => {
if (err) {
res.status(500).send(err);
} else {
res.send('User added.');
}
});
});
// Read
app.get('/users', (req, res) => {
const sql = 'SELECT * FROM users';
db.query(sql, (err, results) => {
if (err) {
res.status(500).send(err);
} else {
res.json(results);
}
});
});
// Update
app.put('/update/:id', (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
const sql = 'UPDATE users SET name = ?, email = ? WHERE id = ?';
db.query(sql, [name, email, id], (err, result) => {
if (err) {
res.status(500).send(err);
} else {
res.send('User updated.');
}
});
});
// Delete
app.delete('/delete/:id', (req, res) => {
const { id } = req.params;
const sql = 'DELETE FROM users WHERE id = ?';
db.query(sql, [id], (err, result) => {
if (err) {
res.status(500).send(err);
} else {
res.send('User deleted.');
}
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Frontend: HTML, CSS, and JavaScript
Create an index.html file to serve as the frontend:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRUD App</title>
<style>
/* Add some basic styling */
</style>
</head>
<body>
<h1>CRUD Application</h1>
<form id="userForm">
<input type="text" id="name" placeholder="Name" required>
<input type="email" id="email" placeholder="Email" required>
<button type="submit">Add User</button>
</form>
<ul id="userList"></ul>
<script>
const userForm = document.getElementById('userForm');
const userList = document.getElementById('userList');
userForm.addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const response = await fetch('http://localhost:3000/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, email })
});
if (response.ok) {
alert('User added.');
fetchUsers();
}
});
async function fetchUsers() {
const response = await fetch('http://localhost:3000/users');
const users = await response.json();
userList.innerHTML = '';
users.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.name} (${user.email})`;
li.innerHTML += ` <button onclick="deleteUser(${user.id})">Delete</button>`;
li.innerHTML += ` <button onclick="editUser(${user.id}, '${user.name}', '${user.email}')">Edit</button>`;
userList.appendChild(li);
});
}
async function deleteUser(id) {
const response = await fetch(`http://localhost:3000/delete/${id}`, { method: 'DELETE' });
if (response.ok) {
alert('User deleted.');
fetchUsers();
}
}
async function editUser(id, name, email) {
const newName = prompt('Enter new name:', name);
const newEmail = prompt('Enter new email:', email);
const response = await fetch(`http://localhost:3000/update/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: newName, email: newEmail })
});
if (response.ok) {
alert('User updated.');
fetchUsers();
}
}
fetchUsers();
</script>
</body>
</html>
Setup MySQL Database
Open your MySQL client and create a database and a table:
CREATE DATABASE crud_db;
USE crud_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
);
Running the Application
Start your Node.js server:
node server.js
Open index.html in your browser.
You now have a basic CRUD application using JavaScript, Node.js, Express, and MySQL. This can be expanded with more features, error handling, and frontend frameworks like React or Vue.js for a more sophisticated application.
☜
☞