How to create a dynamic data table using MySQL and JavaScript
Overview:
In modern web development, dynamic data tables are a very common component. By using the database management system MySQL and the front-end programming language JavaScript, we can easily create a dynamic data table for displaying and manipulating data in the database. This article will introduce in detail how to use MySQL and JavaScript to create a dynamic data table and provide specific code examples.
Steps:
CREATE DATABASE my_database; USE my_database; CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), age INT, email VARCHAR(100) );
const mysql = require('mysql'); const connection = mysql.createConnection({ host : 'localhost', user : 'your_username', password : 'your_password', database : 'my_database' }); connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL database'); });
Please make sure to replaceyour_username
andyour_password
in the above code with your actual MySQL username and password.
const sql = 'SELECT * FROM my_table'; connection.query(sql, (err, result) => { if (err) throw err; console.log('Fetched data from database:', result); // 将数据展示在表格中 const table = document.getElementById('data-table'); result.forEach((row) => { const newRow = table.insertRow(); Object.values(row).forEach((value) => { const cell = newRow.insertCell(); cell.innerHTML = value; }); }); });
In the above example, we executed a simple SELECT statement to obtain all the data in the database and display it in In an HTML table with the IDdata-table
.
const sql = `INSERT INTO my_table (name, age, email) VALUES ('John', 25, 'john@example.com')`; connection.query(sql, (err, result) => { if (err) throw err; console.log('Inserted a new row into the database'); });
The above code will insert a new row of data in themy_table
table of the database.
Summary:
By using MySQL and JavaScript, we can easily create a dynamic data table and display and operate the data in the database. This article provides specific code examples for connecting to the database, querying data, and performing other operations. I hope it will be helpful to everyone when developing dynamic data tables.
The above is the detailed content of How to create a dynamic data table using MySQL and JavaScript. For more information, please follow other related articles on the PHP Chinese website!