• Home
  • /
  • Blog
  • /
  • Database Programming in HTML Using JavaScript Explained to Kids

Database Programming in HTML Using JavaScript Explained to Kids

How To Retrieve Data From Database Using Javascript In HTML

This post is also available in: العربية (Arabic)

Technology is rapidly revolutionizing the modern business scenario and every organization – small, medium-sized, or large – needs an attractive, informative, and engaging website that can offer it maximum visibility. Needless to say, capturing and retaining the attention of users is an absolute challenge. The simple truth is that users get easily fed up if they are bombarded with an overdose of information and a confusing mish-mash of images. In this context, an interactive website is the best way to provide a meaningful and engaging user experience.

Let’s understand how to retrieve data from database using Javascript in HTML.

What is an Interactive Website?

An interactive website is essentially an Internet page that uses different kinds of software to create a rich, interactive experience for the user i.e. it facilitates the user to be actively engaged with the site.  For example, let’s take the case of a website that displays weather forecasts for a specific region. If the website is interactive, it enables the user to type in his/her location and shows the detailed weather report for that region. The website may also display the weather forecasts for various countries across the globe and allows the user to zoom in and focus on specific regions, or manipulate the globe to get a quick glimpse of the weather in different parts of the world.

coding-for-kids-ebook-cover

Get Instant Access To 

Coding For Kids eBook

A must read for every parent

Country
  • Afghanistan 93
  • Albania 355
  • Algeria 213
  • American Samoa 1-684
  • Andorra 376
  • Angola 244
  • Anguilla 1-264
  • Antarctica 672
  • Antigua & Barbuda 1-268
  • Argentina 54
  • Armenia 374
  • Aruba 297
  • Australia 61
  • Austria 43
  • Azerbaijan 994
  • Bahamas 1-242
  • Bahrain 973
  • Bangladesh 880
  • Barbados 1-246
  • Belarus 375
  • Belgium 32
  • Belize 501
  • Benin 229
  • Bermuda 1-441
  • Bhutan 975
  • Bolivia 591
  • Bosnia 387
  • Botswana 267
  • Bouvet Island 47
  • Brazil 55
  • British Indian Ocean Territory 246
  • British Virgin Islands 1-284
  • Brunei 673
  • Bulgaria 359
  • Burkina Faso 226
  • Burundi 257
  • Cambodia 855
  • Cameroon 237
  • Canada 1
  • Cape Verde 238
  • Caribbean Netherlands 599
  • Cayman Islands 1-345
  • Central African Republic 236
  • Chad 235
  • Chile 56
  • China 86
  • Christmas Island 61
  • Cocos (Keeling) Islands 61
  • Colombia 57
  • Comoros 269
  • Congo - Brazzaville 242
  • Congo - Kinshasa 243
  • Cook Islands 682
  • Costa Rica 506
  • Croatia 385
  • Cuba 53
  • Cyprus 357
  • Czech Republic 420
  • Denmark 45
  • Djibouti 253
  • Dominica 1-767
  • Ecuador 593
  • Egypt 20
  • El Salvador 503
  • Equatorial Guinea 240
  • Eritrea 291
  • Estonia 372
  • Ethiopia 251
  • Falkland Islands 500
  • Faroe Islands 298
  • Fiji 679
  • Finland 358
  • France 33
  • French Guiana 594
  • French Polynesia 689
  • French Southern Territories 262
  • Gabon 241
  • Gambia 220
  • Georgia 995
  • Germany 49
  • Ghana 233
  • Gibraltar 350
  • Greece 30
  • Greenland 299
  • Grenada 1-473
  • Guadeloupe 590
  • Guam 1-671
  • Guatemala 502
  • Guernsey 44
  • Guinea 224
  • Guinea-Bissau 245
  • Guyana 592
  • Haiti 509
  • Heard & McDonald Islands 672
  • Honduras 504
  • Hong Kong 852
  • Hungary 36
  • Iceland 354
  • India 91
  • Indonesia 62
  • Iran 98
  • Iraq 964
  • Ireland 353
  • Isle of Man 44
  • Israel 972
  • Italy 39
  • Jamaica 1-876
  • Japan 81
  • Jersey 44
  • Jordan 962
  • Kazakhstan 7
  • Kenya 254
  • Kiribati 686
  • Kuwait 965
  • Kyrgyzstan 996
  • Laos 856
  • Latvia 371
  • Lebanon 961
  • Lesotho 266
  • Liberia 231
  • Libya 218
  • Liechtenstein 423
  • Lithuania 370
  • Luxembourg 352
  • Macau 853
  • Macedonia 389
  • Madagascar 261
  • Malawi 265
  • Malaysia 60
  • Maldives 960
  • Mali 223
  • Malta 356
  • Marshall Islands 692
  • Martinique 596
  • Mauritania 222
  • Mauritius 230
  • Mayotte 262
  • Mexico 52
  • Micronesia 691
  • Moldova 373
  • Monaco 377
  • Mongolia 976
  • Montenegro 382
  • Montserrat 1-664
  • Morocco 212
  • Mozambique 258
  • Myanmar 95
  • Namibia 264
  • Nauru 674
  • Nepal 977
  • Netherlands 31
  • New Caledonia 687
  • New Zealand 64
  • Nicaragua 505
  • Niger 227
  • Nigeria 234
  • Niue 683
  • Norfolk Island 672
  • North Korea 850
  • Northern Mariana Islands 1-670
  • Norway 47
  • Oman 968
  • Pakistan 92
  • Palau 680
  • Palestine 970
  • Panama 507
  • Papua New Guinea 675
  • Paraguay 595
  • Peru 51
  • Philippines 63
  • Pitcairn Islands 870
  • Poland 48
  • Portugal 351
  • Puerto Rico 1
  • Qatar 974
  • Romania 40
  • Russia 7
  • Rwanda 250
  • Réunion 262
  • Samoa 685
  • San Marino 378
  • Saudi Arabia 966
  • Senegal 221
  • Serbia 381 p
  • Seychelles 248
  • Sierra Leone 232
  • Singapore 65
  • Slovakia 421
  • Slovenia 386
  • Solomon Islands 677
  • Somalia 252
  • South Africa 27
  • South Georgia & South Sandwich Islands 500
  • South Korea 82
  • South Sudan 211
  • Spain 34
  • Sri Lanka 94
  • Sudan 249
  • Suriname 597
  • Svalbard & Jan Mayen 47
  • Swaziland 268
  • Sweden 46
  • Switzerland 41
  • Syria 963
  • Sao Tome and Principe 239
  • Taiwan 886
  • Tajikistan 992
  • Tanzania 255
  • Thailand 66
  • Timor-Leste 670
  • Togo 228
  • Tokelau 690
  • Tonga 676
  • Trinidad & Tobago 1-868
  • Tunisia 216
  • Turkey 90
  • Turkmenistan 993
  • Turks & Caicos Islands 1-649
  • Tuvalu 688
  • U.S. Outlying Islands
  • U.S. Virgin Islands 1-340
  • UK 44
  • US 1
  • Uganda 256
  • Ukraine 380
  • United Arab Emirates 971
  • Uruguay 598
  • Uzbekistan 998
  • Vanuatu 678
  • Vatican City 39-06
  • Venezuela 58
  • Vietnam 84
  • Wallis & Futuna 681
  • Western Sahara 212
  • Yemen 967
  • Zambia 260
  • Zimbabwe 263
How Old Is Your Child?
  • Less Than 5 Years
  • 5 - 8 Years
  • 9 - 13 Years
  • 14 - 18 Years
  • 18+ Years

Some of the most common types of interactive websites include Blogs, Forums, Wikis, and Social networks. Interactive websites allow users to change the way the website displays, play games, interact with friends online and perform a host of tasks. This includes:

  • Online transactions
  • Submitting stories, photos, videos, and blogs
  • Interactive features, such as calculators and clickable maps, help the user to explore the various services offered by a company
  • Personalization of content and experience based on history and demographics.
  • Features, such as live chat, pop-ups, and help screens enable context-sensitive, user-friendly help.

In order to create an interactive website, one needs a database connected to the website to provide the required information.

What is a Database?

A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS). Together, the data and the DBMS, along with the applications that are associated with them, are referred to as a database system, often shortened to just a database.

Database Programming in HTML Using JavaScript

Data within the most common types of databases in operation today is typically modeled in rows and columns in a series of tables to make processing and data querying efficient. The data can then be easily accessed, managed, modified, updated, controlled, and organized. Most databases use structured query language (SQL) for writing and querying data.

What is a Web Database?

A web database is a system for storing information that can then be accessed via a website. For example, an online community may have a database that stores the username, password, and other details of all its members. 

At its most simple level, a web database is a set of one or more tables that contain data. Each table has different fields for storing information of various types. These tables can then be linked together in order to manipulate data in useful or interesting ways. In many cases, a table will use a primary key, which must be unique for each entry and allows for an unambiguous selection of data.

How To Retrieve Data From Database Using Javascript In HTML

A web database can be used for a range of different purposes. Each field in a table has to have a defined data type. For example, numbers, strings, and dates can all be inserted into a web database. Proper database design involves choosing the correct data type for each field in order to reduce memory consumption and increase the speed of access. Although for small databases this often isn’t so important, big web databases can grow to millions of entries and need to be well-designed to work effectively.

Content management systems commonly use web databases to store information such as posts, usernames, and comments. Using a database allows the website to be updated easily and without the need to edit the HTML code for each individual page. Not only is this a much more efficient way of creating and updating a website, but it also makes the process more accessible to people who aren’t fluent in the programming languages of the Internet.

An example of where a web database may be used is for an online forum. Forum software often creates a database with a number of tables, including one for users, posts, and settings. It is important for the relationships between the database tables to be properly set and defined so that posts and users can be linked together easily.

Database Programming in HTML Using JavaScript

Node.js can be used in database applications. One of the most popular databases is MySQL. For this, you should have MySQL installed on your computer. You can download a free MySQL database at ttps://www.mysql.com/downloads/.

Once you have MySQL up and running on your computer, you can access it by using Node.js.

To access a MySQL database with Node.js, you need a MySQL driver. This tutorial will use the “MySQL” module, downloaded from NPM.

To download and install the “MySQL” module, open the Command Terminal and execute the following:

C:\Users\YourName\npm install mysql

Now you have downloaded and installed a mysql database driver. Node.js can use this module to manipulate the MySQL database:

var mysql = require('mysql');

How to Connect to Database Using Javascript

The following code is used to connect to database using Javascript.

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

Now, save the code above in a file called “demo_db_connection.js” and run the file:

C:\Users\YourName\node demo_db_connection.js

Now you can start querying the database using SQL statements.

How to Get Data From Database in Javascript

After connecting to a database, let’s see how to get data from database in Javascript. For this use SQL statements to read from (or write to) a MySQL database. This is also called “to query” the database. The connection object created in the example above has a method for querying the database:

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Result: " + result);
  });
});

The query method takes SQL statements as a parameter and returns the result.

Creating a Database

To create a database in MySQL, use the “CREATE DATABASE” statement:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});
 
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
	console.log("Database created");
  });
});

The above code will create a database with the name mydb.

Save the code above in a file called “demo_create_db.js” and run the file:

Creating a Table

To create a table in MySQL, use the “CREATE TABLE” statement. Make sure you define the name of the database when you create the connection:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
	console.log("Table created");
  });
});

The above code creates a table with the name customers.

Save the code above in a file called “demo_create_table.js” and run the file:

C:\Users\YourName\node demo_create_table_db.js

Adding Data to a Table

To fill a table in MySQL, use the “INSERT INTO” statement.

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
  con.query(sql, function (err, result) {
    if (err) throw err;
	console.log("1 record inserted");
  });
});

Save the code above in a file called “demo_db_insert.js”, and run the file:

C:\Users\YourName\node demo_db_insert.js

Retrieving Data from a Table

To select data from a table in MySQL, use the “SELECT” statement.

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
	console.log(result);
  });
});

Save the code above in a file called “demo_db_select.js” and run the file:

C:\Users\YourName\node demo_db_select.js

Filtering Records in a Database

When selecting records from a table, you can filter the selection by using the “WHERE” statement:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers WHERE address = 'Park Lane 38'", function (err, result) {
    if (err) throw err;
	console.log(result);
  });
});

The above code will fetch the record(s) with the address ‘Park Lane 38’.

Save the code above in a file called “demo_db_where.js” and run the file:

C:\Users\YourName\node demo_db_where.js

You can also select the records that start, includes, or ends with a given letter or phrase. Use the ‘%’ wildcard to represent zero, one, or multiple characters:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers WHERE address LIKE 'S%'", function (err, result) {
    if (err) throw err;
	console.log(result);
  });
});

The above code will fetch the record(s) where the address starts with the letter ‘S’.

Save the code above in a file called “demo_db_where_s.js” and run the file:

C:\Users\YourName\node demo_db_where_s.js

When query values are variables provided by the user, you should escape the values. This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database. The MySQL module has methods to escape query values:

var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
con.query(sql, function (err, result) {
  if (err) throw err;
  console.log(result);
});

You can also use a ? as a placeholder for the values you want to escape. In this case, the variable is sent as the second parameter in the query() method:

var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
  if (err) throw err;
  console.log(result);
});

If you have multiple placeholders, the array contains multiple values, in that order:

var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
  if (err) throw err;
  console.log(result);
});

Sorting the Result

Use the ORDER BY statement to sort the result in ascending or descending order. The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers ORDER BY name", function (err, result) {
    if (err) throw err;
	console.log(result);
  });
});

Save the code above in a file called “demo_db_orderby.js” and run the file:

C:\Users\YourName\node demo_db_orderby.js

Deleting Record from a Table

You can delete records from an existing table by using the “DELETE FROM” statement:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
  con.query(sql, function (err, result) {
    if (err) throw err;
	console.log("Number of records deleted: " + result.affectedRows);
  });
});

Save the code above in a file called “demo_db_delete.js” and run the file:

C:\Users\YourName\node demo_db_delete.js

Deleting a Table

You can delete an existing table by using the “DROP TABLE” statement:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  var sql = "DROP TABLE customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
	console.log("Table deleted");
  });
});

Save the code above in a file called “demo_db_drop_table.js” and run the file:

C:\Users\YourName\node demo_db_drop_table.js

Updating a Table

You can update existing records in a table by using the “UPDATE” statement:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'";
  con.query(sql, function (err, result) {
    if (err) throw err;
	console.log(result.affectedRows + " record(s) updated");
  });
});

Save the code above in a file called “demo_db_update.js” and run the file:

C:\Users\YourName\node demo_db_update.js

Practice Problems

  1. What is meant by Interactive Website?
  2. What is a Database?
  3. What is a Web Database?
  4. What is MySql?
  5. What is meant by query?
  6. What is a table in a database and how it is created?
  7. What is the function of the INSERT statement and what is its syntax?
  8. What is the function of the SELECT statement and what is its syntax?
  9. What is the function of the WHERE clause?

FAQs

What is a database in HTML?

A hypertext markup language (HTML) database is a program that can collect and display information over the Internet. This database software interfaces with the Internet programming language to enable website visitors to search a collection of information or enter information into a Web form to be added to the database.

What is database programming for websites?

Software that is used to manage data and information structured as fields, records, and files. A database program is the heart of a business information system and provides file creation, data entry, update, query, and reporting functions.

Can HTML interact with the database?

You can’t make HTML directly interact with the database. You should create a server-side application, which answers queries generated by HTML forms, JS queries, etc.

Conclusion

A database program is the heart of a business information system and provides file creation, data entry, update, query, and reporting functions. Database programming in HTML makes the websites interactive by facilitating users to interact with them.

Recommended Reading

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>