How to Connect to Database in Javascript (Simple Examples)

Welcome to a tutorial on how to connect to a database in Javascript. Need to connect to the database in Javascript to fetch or save some data?

It is possible to connect to a database with modern Javascript, but it is a different process depending on where you are applying it to:

  • On web pages (client-side Javascript), the usual practice is to make an AJAX call to a server-side script that will connect to the database.
  • In NodeJS (server-side Javascript), we can easily connect to a database using the respective database module.

So just how exactly do we connect to the database in the above cases? Let us walk through some examples and alternatives – Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes JS Database NodeJS Database
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

DATABASE CONNECTION VIA AJAX (CLIENT-SIDE JS)

If you are working with a webpage, it is called “client-side Javascript” because it runs on the user’s device. In this case, we make an intermediary AJAX call to a server-side script that will connect to the database. Take note, this is based on PHP MySQL, I will leave more links below for other languages and databases.

 

STEP 1) DUMMY DATABASE TABLE

1a-dummy.sql
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD KEY `user_name` (`user_name`);

ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

INSERT INTO `users` (`user_id`, `user_name`) VALUES
  (1, 'John Doe'),
  (2, 'Jane Doe'),
  (3, 'Johan Doe');

For the purpose of demonstration, we will use this dummy user table – Just 2 fields here, the user ID and name.

 

STEP 2) SERVER-SIDE SCRIPT (THAT CONNECTS TO DATABASE)

1b-database.php
<?php
// (A) SETTINGS - CHANGE TO YOUR OWN !
error_reporting(E_ALL & ~E_NOTICE);
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (B) CONNECT TO DATABASE
try {
  $pdo = new PDO(
    "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME, 
    DB_USER, DB_PASSWORD
  );
} catch (Exception $ex) { exit($ex->getMessage()); }

// (C) GET USERS
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
$users = $stmt->fetchAll();
foreach ($users as $u) {
  printf("<div>[%u] %s</div>", $u['user_id'], $u['user_name']);
}

// (D) CLOSE DATABASE CONNECTION
$pdo = null;
$stmt = null;

Next, this server-side script will connect to the database. It simply gets all the users from the database and outputs them in HTML.

 

 

STEP 3) HTML & JAVASCRIPT (CALL SERVER-SIDE SCRIPT)

1c-javascript.html
<!-- (A) LIST USERS HERE -->
<div id="demo"></div>

<!-- (B) FETCH USERS VIA AJAX -->
<script>
// NOTE: RUN WITH HTTP://, NOT FILE://
window.addEventListener("load", () => {
  fetch("1b-database.php", { method : "POST" })
  .then(res => res.text()).then((txt) => {
    document.getElementById("demo").innerHTML = txt;
  });
});
</script>

Finally, all that’s left is to use Javascript on the webpage to make an AJAX fetch call to the server-side script.

P.S. AJAX stands for Asynchronous Javascript and XML. In simple terms, “load data without refreshing the entire page”.

 

WHY THE ROUNDABOUT METHOD?

So why this “dumb roundabout” way of using Javascript to call a server-side script, then to the database? Isn’t it simpler for Javascript to just directly connect to the database? Well, that is possible, but the key consideration here is security. For Javascript to make a direct connection to the database:

  • The database will have to be directly exposed to the Internet to accept connections.
  • The database user and password have to be “hardcoded” in Javascript.
  • Being client-side in this case, the source code and user/password are fully visible to all users.

This is why keeping database connections behind the server-side script makes more sense. Users don’t get to see the user/password, and cannot directly mess with the database.

 

 

NODEJS CONNECT TO DATABASE (SERVER-SIDE JS)

Working with server-side NodeJS? Here is how to connect to a database in NodeJS. Take note again, this example is using MySQL, but NodeJS also supports other databases such as MSSQL and MongoDB.

 

STEP 1) INSTALL THE DATABASE MODULE

First, navigate to your project folder in the command line, and install the database module:

D:\YOUR\PROJECT> npm install mysql

For the sake of simplicity, we are just going to reuse the above dummy database table and MySQL. If you are not planning to use MySQL, there are also several other Node Database Modules:

 

STEP 2) THE SCRIPT

2-node-db.js
// (A) LOAD DB MODULE
const mysql = require("mysql");

// (B) CREATE CONNECTION - CHANGE TO YOUR OWN !
const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "test"
});
db.connect((err) => {
  if (err) { throw err; }
  console.log("DB connection OK");
});

// (C) QUERY
db.query("SELECT * FROM `users`", (err, results) => {
  if (err) { throw err; }
  console.log(results);
});

Yep, it’s that simple – Just load the database module and make a connection. But take note that this is based on MySQL again, install and load your own if you are using something else.

 

 

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

ALTERNATIVE) LOCAL STORAGE 

3-localstorage.html
// (A) DATA OBJECT
var user = {
  name : "John Doe",
  email : "john@doe.com",
  gender : "Doe"
};
 
// (B) STORE IN LOCAL STORAGE
// Note: JSON encode
localStorage.setItem("User", JSON.stringify(user));
 
// (C) RETRIEVE
// Note: JSON decode
user = localStorage.getItem("User");
user = JSON.parse(user);
console.log(user);

If you only need some simple temporary storage for your website, you don’t need a full database. Here’s how we can store some simple variables using the Web Storage API, there are only 4 operations:

  • localStorage.setItem(KEY, VALUE) – Saves data into the local storage.
  • localStorage.getItem(KEY) – Retrieves data from the local storage.
  • localStorage.removeItem(KEY) – Removes data from the local storage.
  • localStorage.clear() – Remove everything.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Connect Javascript To MySQL Database (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “How to Connect to Database in Javascript (Simple Examples)”

  1. Thank you so much for this. I have a few php/postgres apps I want to change over to JavaScript and postgres. I’m just learning how to code in the apps that I created were done using PHPrunner. It’s a wonderful tool but requires no code knowledge to be productive.

    So it’s time to put on my big boy pants and learn how to code and that’s why I’m using JavaScript but keeping my postgres databases. Most of my logic and functionality is built into the database and I don’t want to lose that.
    Thank you.

Leave a Comment

Your email address will not be published.